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
|
---|---|---|---|---|---|
6a841823648aa971f6b24db0fd5a249392ddd733 | 1,006 | # encoding: UTF-8
# This file is auto-generated from the current state of the database. Instead
# of editing this file, please use the migrations feature of Active Record to
# incrementally modify your database, and then regenerate this schema definition.
#
# Note that this schema.rb definition is the authoritative source for your
# database schema. If you need to create the application database on another
# system, you should be using db:schema:load, not running all the migrations
# from scratch. The latter is a flawed and unsustainable approach (the more migrations
# you'll amass, the slower it'll run and the greater likelihood for issues).
#
# It's strongly recommended that you check this file into your version control system.
ActiveRecord::Schema.define(version: 20160808001835) do
create_table "songs", force: :cascade do |t|
t.string "title"
t.string "key"
t.text "chords"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
end
| 40.24 | 86 | 0.754473 |
1d59525f2895014acd9ff97b60cdd5b9adc7307d | 2,652 | require 'administrate/base_dashboard'
class UserDashboard < Administrate::BaseDashboard
# ATTRIBUTE_TYPES
# a hash that describes the type of each of the model's fields.
#
# Each different type represents an Administrate::Field object,
# which determines how the attribute is displayed
# on pages throughout the dashboard.
ATTRIBUTE_TYPES = {
account_users: Field::HasMany,
id: Field::Number,
avatar_url: AvatarField,
provider: Field::String,
uid: Field::String,
password: Field::Password,
sign_in_count: Field::Number,
current_sign_in_at: Field::DateTime,
last_sign_in_at: Field::DateTime,
current_sign_in_ip: Field::String,
last_sign_in_ip: Field::String,
confirmation_token: Field::String,
confirmed_at: Field::DateTime,
confirmation_sent_at: Field::DateTime,
unconfirmed_email: Field::String,
name: Field::String,
display_name: Field::String,
email: Field::String,
tokens: Field::String.with_options(searchable: false),
created_at: Field::DateTime,
updated_at: Field::DateTime,
pubsub_token: Field::String,
type: Field::Select.with_options(collection: [nil, 'SuperAdmin']),
accounts: CountField
}.freeze
# COLLECTION_ATTRIBUTES
# an array of attributes that will be displayed on the model's index page.
#
# By default, it's limited to four items to reduce clutter on index pages.
# Feel free to add, remove, or rearrange items.
COLLECTION_ATTRIBUTES = %i[
id
avatar_url
name
email
accounts
type
].freeze
# SHOW_PAGE_ATTRIBUTES
# an array of attributes that will be displayed on the model's show page.
SHOW_PAGE_ATTRIBUTES = %i[
id
avatar_url
unconfirmed_email
name
type
display_name
email
created_at
updated_at
confirmed_at
account_users
].freeze
# FORM_ATTRIBUTES
# an array of attributes that will be displayed
# on the model's form (`new` and `edit`) pages.
FORM_ATTRIBUTES = %i[
name
display_name
email
password
confirmed_at
type
].freeze
# COLLECTION_FILTERS
# a hash that defines filters that can be used while searching via the search
# field of the dashboard.
#
# For example to add an option to search for open resources by typing "open:"
# in the search field:
#
# COLLECTION_FILTERS = {
# open: ->(resources) { resources.where(open: true) }
# }.freeze
COLLECTION_FILTERS = {}.freeze
# Overwrite this method to customize how users are displayed
# across all pages of the admin dashboard.
#
def display_resource(user)
"##{user.id} #{user.name}"
end
end
| 27.061224 | 79 | 0.697964 |
21aac7319112e2d8b9deb89b328994e3b5e3f9ed | 1,980 | maximum_cost = nil
minimum_cost = nil
@annual_cost_before_and_after.each do |year, before_after|
yearly_maximum = before_after[:before] > before_after[:after] ? before_after[:before] : before_after[:after]
yearly_minimum = before_after[:before] < before_after[:after] ? before_after[:before] : before_after[:after]
unless maximum_cost.blank?
maximum_cost = yearly_maximum > maximum_cost ? yearly_maximum : maximum_cost
else
maximum_cost = yearly_maximum
end
unless minimum_cost.blank?
minimum_cost = yearly_minimum < minimum_cost ? yearly_minimum : minimum_cost
else
minimum_cost = yearly_minimum
end
end
xml.chart(:caption => 'Annual Cost', :xAxisName => 'Year', :yAxisName => 'Annual cost', :showValues => '0', :decimals => '0', :numberPrefix => '$', :showAlternateHGridColor => '0', :divLineColor => 'cccccc', :showBorder => '0', :borderThickness => '0', :adjustDiv => '0', :yAxisMinValue => minimum_cost, :yAxisMaxValue => maximum_cost, :canvasBorderThickness => '1', :canvasBorderColor => 'cccccc', :bgColor => 'ffffff', :bgAlpha => '100') do
xml.categories do
@annual_cost_before_and_after.keys.sort.each do |year|
show_label = year > 1 && year % 5 > 0 ? '0' : '1'
xml.category(:label => year, :showLabel => show_label)
end
end
xml.dataset(:seriesName => 'Before installation', :lineThickness => '1', :color => '6a4600') do
@annual_cost_before_and_after.keys.sort.each do |year|
cost = @annual_cost_before_and_after[year][:before]
xml.set(:value => cost, :toolText => "#{number_to_currency(cost, :precision => 0)} at year #{year}")
end
end
xml.dataset(:seriesName => 'After installation', :lineThickness => '1', :color => '00a021') do
@annual_cost_before_and_after.keys.sort.each do |year|
cost = @annual_cost_before_and_after[year][:after]
xml.set(:value => cost, :toolText => "#{number_to_currency(cost, :precision => 0)} at year #{year}")
end
end
end | 48.292683 | 442 | 0.685354 |
ac81eb3bbc5bee16bf37da609ec80530d455b66a | 1,295 | module Coupler::API
class ComparatorController < Controller
def initialize(index, create, update, show, delete, create_params, update_params, show_params)
@index = index
@create = create
@update = update
@show = show
@delete = delete
@create_params = create_params
@update_params = update_params
@show_params = show_params
end
def self.dependencies
[
'Comparators::Index', 'Comparators::Create', 'Comparators::Update',
'Comparators::Show', 'Comparators::Delete', 'ComparatorParams::Create',
'ComparatorParams::Update', 'ComparatorParams::Show'
]
end
def index(req, res)
@index.run
end
def create(req, res)
data = JSON.parse(req.body.read)
params = @create_params.process(data)
@create.run(params)
end
def update(req, res)
data = JSON.parse(req.body.read)
data['id'] = req['comparator_id']
params = @update_params.process(data)
@update.run(params)
end
def show(req, res)
params = @show_params.process({ 'id' => req['comparator_id'] })
@show.run(params)
end
def delete(req, res)
params = @show_params.process({ 'id' => req['comparator_id'] })
@delete.run(params)
end
end
end
| 25.9 | 98 | 0.617761 |
edf2d91b222cf96b7849d5fa0e4be53b265263dc | 240 | class DemoRequestSystemMailer < Struct.new(:demo_request_id)
def perform()
demo_request = DemoRequest.find(demo_request_id)
# send email to support
SupportMailer.demo_request(demo_request).deliver
end
end
| 18.461538 | 60 | 0.716667 |
39a01cbb814dd5c31f3b1e1c1fdf8defd51cef8a | 2,183 | module ProfileHelper
def countries
Country.pluck(:name, :id)
end
def dial_codes
Country.dial_codes
end
def user_org_admin?
return false if @context.guest?
current_user.id == current_user.org.admin_id
end
# Checks if current user has created organization leave (or leave on dissolve) request.
# @return [true, false] Returns true if user has created organization leave request,
# false otherwise.
def active_leave_org_request_present?
return false if @context.guest?
current_user.active_leave_org_request.present?
end
def leave_org_label
leave = current_user.active_leave_org_request
if leave.nil?
"Leave organization"
elsif leave.new?
"Pending approval for organization leaving"
elsif leave.approved?
"Leaving is approved"
end
end
# @return [String] Returns dissolve button text
def dissolve_org_btn_text
dissolve_request = current_user.org.dissolve_org_action_request
if dissolve_request.nil?
"Dissolve organization"
elsif dissolve_request.new?
"Pending approval for organization dissolving"
elsif dissolve_request.approved?
"Dissolving is approved"
end
end
# @return [true, false] Returns true if dissolve button should be shown,
# false otherwise.
def dissolve_button_shown?
[
OrgActionRequest::State::APPROVED,
OrgActionRequest::State::NEW,
nil
].include?(current_user.org.dissolve_org_action_request&.state)
end
def active_remove_member_request_present?(member)
OrgActionRequest.exists?(
member: member,
action_type: OrgActionRequest::Type::REMOVE_MEMBER,
)
end
def remove_member_label(member)
remove_request = OrgActionRequest.find_by(
member: member,
action_type: OrgActionRequest::Type::REMOVE_MEMBER
)
if remove_request.new?
"Pending approval for member removing"
elsif remove_request.approved?
"Removing is approved"
end
end
def user_exists_attribute(invitation, attribute)
if invitation.user
User.user_helper_attribute(invitation.user_id, attribute)
else
invitation[attribute]
end
end
end
| 25.091954 | 89 | 0.721942 |
ed22123c7c6089a6cf4e4f576373dbd6aff9bf25 | 1,107 | require "spec_helper"
describe GW2::Recipe do
describe ".all" do
before :each do
@recipes = [1275, 1276, 1277, 1278, 1279]
end
it "exists" do
expect(GW2::Recipe.respond_to?(:all)).to eq(true)
end
it "returns all recipes", :vcr do
expect(GW2::Recipe.all).to include(*@recipes)
end
end
describe ".details" do
before :each do
@recipe_details = {
"type" => "Coat",
"output_item_id" => 11541,
"output_item_count" => 1,
"min_rating" => 25,
"time_to_craft_ms" => 1000,
"chat_link" => "[&CfsEAAA=]",
"disciplines" => ["Leatherworker"],
"flags" => [],
"ingredients" => [
{"item_id" => 19797, "count" => 1},
{"item_id" => 13094, "count" => 1},
{"item_id" => 13093, "count" => 1}
],
"id" => 1275
}
end
it "exists" do
expect(GW2::Recipe.respond_to?(:details)).to eq(true)
end
it "returns the details of a recipe by id", :vcr do
expect(GW2::Recipe.details(1275)).to eq(@recipe_details)
end
end
end
| 23.553191 | 62 | 0.530262 |
08e94882b972ecdc3066d548815f24059c2d9a25 | 84 | class UserDetail < ApplicationRecord
belongs_to :user, foreign_key: "user_id"
end
| 21 | 42 | 0.797619 |
87a9b603d1b6b7679d509618beba04f0b5eb8c09 | 73,581 | # -*- coding: utf-8 -*-
#--
# Copyright 2006 by Chad Fowler, Rich Kilmer, Jim Weirich and others.
# All rights reserved.
# See LICENSE.txt for permissions.
#++
require 'rubygems/version'
require 'rubygems/requirement'
require 'rubygems/platform'
require 'rubygems/deprecate'
require 'rubygems/basic_specification'
require 'rubygems/stub_specification'
require 'rubygems/util/stringio'
##
# The Specification class contains the information for a Gem. Typically
# defined in a .gemspec file or a Rakefile, and looks like this:
#
# Gem::Specification.new do |s|
# s.name = 'example'
# s.version = '0.1.0'
# s.licenses = ['MIT']
# s.summary = "This is an example!"
# s.description = "Much longer explanation of the example!"
# s.authors = ["Ruby Coder"]
# s.email = 'rubycoder@example.com'
# s.files = ["lib/example.rb"]
# s.homepage = 'https://rubygems.org/gems/example'
# end
#
# Starting in RubyGems 2.0, a Specification can hold arbitrary
# metadata. See #metadata for restrictions on the format and size of metadata
# items you may add to a specification.
class Gem::Specification < Gem::BasicSpecification
# REFACTOR: Consider breaking out this version stuff into a separate
# module. There's enough special stuff around it that it may justify
# a separate class.
##
# The version number of a specification that does not specify one
# (i.e. RubyGems 0.7 or earlier).
NONEXISTENT_SPECIFICATION_VERSION = -1
##
# The specification version applied to any new Specification instances
# created. This should be bumped whenever something in the spec format
# changes.
#
# Specification Version History:
#
# spec ruby
# ver ver yyyy-mm-dd description
# -1 <0.8.0 pre-spec-version-history
# 1 0.8.0 2004-08-01 Deprecated "test_suite_file" for "test_files"
# "test_file=x" is a shortcut for "test_files=[x]"
# 2 0.9.5 2007-10-01 Added "required_rubygems_version"
# Now forward-compatible with future versions
# 3 1.3.2 2009-01-03 Added Fixnum validation to specification_version
# 4 1.9.0 2011-06-07 Added metadata
#--
# When updating this number, be sure to also update #to_ruby.
#
# NOTE RubyGems < 1.2 cannot load specification versions > 2.
CURRENT_SPECIFICATION_VERSION = 4 # :nodoc:
##
# An informal list of changes to the specification. The highest-valued
# key should be equal to the CURRENT_SPECIFICATION_VERSION.
SPECIFICATION_VERSION_HISTORY = { # :nodoc:
-1 => ['(RubyGems versions up to and including 0.7 did not have versioned specifications)'],
1 => [
'Deprecated "test_suite_file" in favor of the new, but equivalent, "test_files"',
'"test_file=x" is a shortcut for "test_files=[x]"'
],
2 => [
'Added "required_rubygems_version"',
'Now forward-compatible with future versions',
],
3 => [
'Added Fixnum validation to the specification_version'
],
4 => [
'Added sandboxed freeform metadata to the specification version.'
]
}
MARSHAL_FIELDS = { # :nodoc:
-1 => 16,
1 => 16,
2 => 16,
3 => 17,
4 => 18,
}
today = Time.now.utc
TODAY = Time.utc(today.year, today.month, today.day) # :nodoc:
LOAD_CACHE = {} # :nodoc:
private_constant :LOAD_CACHE if defined? private_constant
# :startdoc:
##
# List of attribute names: [:name, :version, ...]
@@required_attributes = [:rubygems_version,
:specification_version,
:name,
:version,
:date,
:summary,
:require_paths]
##
# Map of attribute names to default values.
@@default_value = {
:authors => [],
:autorequire => nil,
:bindir => 'bin',
:cert_chain => [],
:date => TODAY,
:dependencies => [],
:description => nil,
:email => nil,
:executables => [],
:extensions => [],
:extra_rdoc_files => [],
:files => [],
:homepage => nil,
:licenses => [],
:metadata => {},
:name => nil,
:platform => Gem::Platform::RUBY,
:post_install_message => nil,
:rdoc_options => [],
:require_paths => ['lib'],
:required_ruby_version => Gem::Requirement.default,
:required_rubygems_version => Gem::Requirement.default,
:requirements => [],
:rubyforge_project => nil,
:rubygems_version => Gem::VERSION,
:signing_key => nil,
:specification_version => CURRENT_SPECIFICATION_VERSION,
:summary => nil,
:test_files => [],
:version => nil,
}
Dupable = { } # :nodoc:
@@default_value.each do |k,v|
case v
when Time, Numeric, Symbol, true, false, nil
Dupable[k] = false
else
Dupable[k] = true
end
end
@@attributes = @@default_value.keys.sort_by { |s| s.to_s }
@@array_attributes = @@default_value.reject { |k,v| v != [] }.keys
@@nil_attributes, @@non_nil_attributes = @@default_value.keys.partition { |k|
@@default_value[k].nil?
}
######################################################################
# :section: Required gemspec attributes
##
# This gem's name.
#
# Usage:
#
# spec.name = 'rake'
attr_accessor :name
##
# This gem's version.
#
# The version string can contain numbers and periods, such as +1.0.0+.
# A gem is a 'prerelease' gem if the version has a letter in it, such as
# +1.0.0.pre+.
#
# Usage:
#
# spec.version = '0.4.1'
attr_reader :version
##
# Paths in the gem to add to <code>$LOAD_PATH</code> when this gem is
# activated.
#
# See also #require_paths
#
# If you have an extension you do not need to add <code>"ext"</code> to the
# require path, the extension build process will copy the extension files
# into "lib" for you.
#
# The default value is <code>"lib"</code>
#
# Usage:
#
# # If all library files are in the root directory...
# spec.require_paths = ['.']
def require_paths=(val)
@require_paths = Array(val)
end
##
# The version of RubyGems used to create this gem.
#
# Do not set this, it is set automatically when the gem is packaged.
attr_accessor :rubygems_version
##
# A short summary of this gem's description. Displayed in `gem list -d`.
#
# The #description should be more detailed than the summary.
#
# Usage:
#
# spec.summary = "This is a small summary of my gem"
attr_reader :summary
##
# Singular writer for #authors
#
# Usage:
#
# spec.author = 'John Jones'
def author= o
self.authors = [o]
end
##
# Sets the list of authors, ensuring it is an array.
#
# Usage:
#
# spec.authors = ['John Jones', 'Mary Smith']
def authors= value
@authors = Array(value).flatten.grep(String)
end
##
# The platform this gem runs on.
#
# This is usually Gem::Platform::RUBY or Gem::Platform::CURRENT.
#
# Most gems contain pure Ruby code; they should simply leave the default
# value in place. Some gems contain C (or other) code to be compiled into a
# Ruby "extension". The gem should leave the default value in place unless
# the code will only compile on a certain type of system. Some gems consist
# of pre-compiled code ("binary gems"). It's especially important that they
# set the platform attribute appropriately. A shortcut is to set the
# platform to Gem::Platform::CURRENT, which will cause the gem builder to set
# the platform to the appropriate value for the system on which the build is
# being performed.
#
# If this attribute is set to a non-default value, it will be included in
# the filename of the gem when it is built such as:
# nokogiri-1.6.0-x86-mingw32.gem
#
# Usage:
#
# spec.platform = Gem::Platform.local
def platform= platform
if @original_platform.nil? or
@original_platform == Gem::Platform::RUBY then
@original_platform = platform
end
case platform
when Gem::Platform::CURRENT then
@new_platform = Gem::Platform.local
@original_platform = @new_platform.to_s
when Gem::Platform then
@new_platform = platform
# legacy constants
when nil, Gem::Platform::RUBY then
@new_platform = Gem::Platform::RUBY
when 'mswin32' then # was Gem::Platform::WIN32
@new_platform = Gem::Platform.new 'x86-mswin32'
when 'i586-linux' then # was Gem::Platform::LINUX_586
@new_platform = Gem::Platform.new 'x86-linux'
when 'powerpc-darwin' then # was Gem::Platform::DARWIN
@new_platform = Gem::Platform.new 'ppc-darwin'
else
@new_platform = Gem::Platform.new platform
end
@platform = @new_platform.to_s
invalidate_memoized_attributes
@new_platform
end
##
# Files included in this gem. You cannot append to this accessor, you must
# assign to it.
#
# Only add files you can require to this list, not directories, etc.
#
# Directories are automatically stripped from this list when building a gem,
# other non-files cause an error.
#
# Usage:
#
# require 'rake'
# spec.files = FileList['lib/**/*.rb',
# 'bin/*',
# '[A-Z]*',
# 'test/**/*'].to_a
#
# # or without Rake...
# spec.files = Dir['lib/**/*.rb'] + Dir['bin/*']
# spec.files += Dir['[A-Z]*'] + Dir['test/**/*']
# spec.files.reject! { |fn| fn.include? "CVS" }
def files
# DO NOT CHANGE TO ||= ! This is not a normal accessor. (yes, it sucks)
# DOC: Why isn't it normal? Why does it suck? How can we fix this?
@files = [@files,
@test_files,
add_bindir(@executables),
@extra_rdoc_files,
@extensions,
].flatten.uniq.compact.sort
end
######################################################################
# :section: Optional gemspec attributes
##
# The path in the gem for executable scripts. Usually 'bin'
#
# Usage:
#
# spec.bindir = 'bin'
attr_accessor :bindir
##
# The certificate chain used to sign this gem. See Gem::Security for
# details.
attr_accessor :cert_chain
##
# A long description of this gem
#
# The description should be more detailed than the summary but not
# excessively long. A few paragraphs is a recommended length with no
# examples or formatting.
#
# Usage:
#
# spec.description = <<-EOF
# Rake is a Make-like program implemented in Ruby. Tasks and
# dependencies are specified in standard Ruby syntax.
# EOF
attr_reader :description
##
# A contact email address (or addresses) for this gem
#
# Usage:
#
# spec.email = 'john.jones@example.com'
# spec.email = ['jack@example.com', 'jill@example.com']
attr_accessor :email
##
# The URL of this gem's home page
#
# Usage:
#
# spec.homepage = 'http://rake.rubyforge.org'
attr_accessor :homepage
##
# A message that gets displayed after the gem is installed.
#
# Usage:
#
# spec.post_install_message = "Thanks for installing!"
attr_accessor :post_install_message
##
# The version of Ruby required by this gem
attr_reader :required_ruby_version
##
# The RubyGems version required by this gem
attr_reader :required_rubygems_version
##
# The key used to sign this gem. See Gem::Security for details.
attr_accessor :signing_key
##
# :attr_accessor: metadata
#
# The metadata holds extra data for this gem that may be useful to other
# consumers and is settable by gem authors without requiring an update to
# the rubygems software.
#
# Metadata items have the following restrictions:
#
# * The metadata must be a Hash object
# * All keys and values must be Strings
# * Keys can be a maximum of 128 bytes and values can be a maximum of 1024
# bytes
# * All strings must be UTF-8, no binary data is allowed
#
# To add metadata for the location of a issue tracker:
#
# s.metadata = { "issue_tracker" => "https://example/issues" }
attr_accessor :metadata
##
# Adds a development dependency named +gem+ with +requirements+ to this
# gem.
#
# Usage:
#
# spec.add_development_dependency 'example', '~> 1.1', '>= 1.1.4'
#
# Development dependencies aren't installed by default and aren't
# activated when a gem is required.
def add_development_dependency(gem, *requirements)
add_dependency_with_type(gem, :development, *requirements)
end
##
# Adds a runtime dependency named +gem+ with +requirements+ to this gem.
#
# Usage:
#
# spec.add_runtime_dependency 'example', '~> 1.1', '>= 1.1.4'
def add_runtime_dependency(gem, *requirements)
add_dependency_with_type(gem, :runtime, *requirements)
end
##
# Executables included in the gem.
#
# For example, the rake gem has rake as an executable. You don’t specify the
# full path (as in bin/rake); all application-style files are expected to be
# found in bindir. These files must be executable Ruby files. Files that
# use bash or other interpreters will not work.
#
# Executables included may only be ruby scripts, not scripts for other
# languages or compiled binaries.
#
# Usage:
#
# spec.executables << 'rake'
def executables
@executables ||= []
end
##
# Extensions to build when installing the gem, specifically the paths to
# extconf.rb-style files used to compile extensions.
#
# These files will be run when the gem is installed, causing the C (or
# whatever) code to be compiled on the user’s machine.
#
# Usage:
#
# spec.extensions << 'ext/rmagic/extconf.rb'
#
# See Gem::Ext::Builder for information about writing extensions for gems.
def extensions
@extensions ||= []
end
##
# Extra files to add to RDoc such as README or doc/examples.txt
#
# When the user elects to generate the RDoc documentation for a gem (typically
# at install time), all the library files are sent to RDoc for processing.
# This option allows you to have some non-code files included for a more
# complete set of documentation.
#
# Usage:
#
# spec.extra_rdoc_files = ['README', 'doc/user-guide.txt']
def extra_rdoc_files
@extra_rdoc_files ||= []
end
##
# The version of RubyGems that installed this gem. Returns
# <code>Gem::Version.new(0)</code> for gems installed by versions earlier
# than RubyGems 2.2.0.
def installed_by_version # :nodoc:
@installed_by_version ||= Gem::Version.new(0)
end
##
# Sets the version of RubyGems that installed this gem. See also
# #installed_by_version.
def installed_by_version= version # :nodoc:
@installed_by_version = Gem::Version.new version
end
##
# :category: Recommended gemspec attributes
#
# The license for this gem.
#
# The license must be no more than 64 characters.
#
# This should just be the name of your license. The full text of the license
# should be inside of the gem (at the top level) when you build it.
#
# The simplest way, is to specify the standard SPDX ID
# https://spdx.org/licenses/ for the license.
# Ideally you should pick one that is OSI (Open Source Initiative)
# http://opensource.org/licenses/alphabetical approved.
#
# The most commonly used OSI approved licenses are BSD-3-Clause and MIT.
# GitHub also provides a license picker at http://choosealicense.com/.
#
# You should specify a license for your gem so that people know how they are
# permitted to use it, and any restrictions you're placing on it. Not
# specifying a license means all rights are reserved; others have no rights
# to use the code for any purpose.
#
# You can set multiple licenses with #licenses=
#
# Usage:
# spec.license = 'MIT'
def license=o
self.licenses = [o]
end
##
# :category: Recommended gemspec attributes
# The license(s) for the library.
#
# Each license must be a short name, no more than 64 characters.
#
# This should just be the name of your license. The full
# text of the license should be inside of the gem when you build it.
#
# See #license= for more discussion
#
# Usage:
# spec.licenses = ['MIT', 'GPL-2']
def licenses= licenses
@licenses = Array licenses
end
##
# Specifies the rdoc options to be used when generating API documentation.
#
# Usage:
#
# spec.rdoc_options << '--title' << 'Rake -- Ruby Make' <<
# '--main' << 'README' <<
# '--line-numbers'
def rdoc_options
@rdoc_options ||= []
end
##
# The version of Ruby required by this gem. The ruby version can be
# specified to the patch-level:
#
# $ ruby -v -e 'p Gem.ruby_version'
# ruby 2.0.0p247 (2013-06-27 revision 41674) [x86_64-darwin12.4.0]
# #<Gem::Version "2.0.0.247">
#
# Usage:
#
# # This gem will work with 1.8.6 or greater...
# spec.required_ruby_version = '>= 1.8.6'
#
# # Only with ruby 2.0.x
# spec.required_ruby_version = '~> 2.0'
def required_ruby_version= req
@required_ruby_version = Gem::Requirement.create req
end
##
# The RubyGems version required by this gem
def required_rubygems_version= req
@required_rubygems_version = Gem::Requirement.create req
end
##
# Lists the external (to RubyGems) requirements that must be met for this gem
# to work. It's simply information for the user.
#
# Usage:
#
# spec.requirements << 'libmagick, v6.0'
# spec.requirements << 'A good graphics card'
def requirements
@requirements ||= []
end
##
# A collection of unit test files. They will be loaded as unit tests when
# the user requests a gem to be unit tested.
#
# Usage:
# spec.test_files = Dir.glob('test/tc_*.rb')
# spec.test_files = ['tests/test-suite.rb']
def test_files= files # :nodoc:
@test_files = Array files
end
######################################################################
# :section: Specification internals
##
# True when this gemspec has been activated. This attribute is not persisted.
attr_accessor :activated
alias :activated? :activated
##
# Autorequire was used by old RubyGems to automatically require a file.
#
# Deprecated: It is neither supported nor functional.
attr_accessor :autorequire # :nodoc:
##
# Sets the default executable for this gem.
#
# Deprecated: You must now specify the executable name to Gem.bin_path.
attr_writer :default_executable
##
# Allows deinstallation of gems with legacy platforms.
attr_writer :original_platform # :nodoc:
##
# The rubyforge project this gem lives under. i.e. RubyGems'
# rubyforge_project is "rubygems".
#
# This option is deprecated.
attr_accessor :rubyforge_project
##
# The Gem::Specification version of this gemspec.
#
# Do not set this, it is set automatically when the gem is packaged.
attr_accessor :specification_version
def self._all # :nodoc:
unless defined?(@@all) && @@all then
@@all = stubs.map(&:to_spec)
# After a reset, make sure already loaded specs
# are still marked as activated.
specs = {}
Gem.loaded_specs.each_value{|s| specs[s] = true}
@@all.each{|s| s.activated = true if specs[s]}
_resort!(@@all)
end
@@all
end
def self._clear_load_cache # :nodoc:
LOAD_CACHE.clear
end
def self.each_gemspec(dirs) # :nodoc:
dirs.each do |dir|
Dir[File.join(dir, "*.gemspec")].each do |path|
yield path.untaint
end
end
end
def self.each_stub(dirs) # :nodoc:
each_gemspec(dirs) do |path|
stub = Gem::StubSpecification.new(path)
yield stub if stub.valid?
end
end
def self.each_spec(dirs) # :nodoc:
each_gemspec(dirs) do |path|
spec = self.load path
yield spec if spec
end
end
##
# Returns a Gem::StubSpecification for every installed gem
def self.stubs
@@stubs ||= begin
stubs = {}
each_stub([default_specifications_dir] + dirs) do |stub|
stubs[stub.full_name] ||= stub
end
stubs = stubs.values
_resort!(stubs)
stubs
end
end
def self._resort!(specs) # :nodoc:
specs.sort! { |a, b|
names = a.name <=> b.name
next names if names.nonzero?
b.version <=> a.version
}
end
##
# Loads the default specifications. It should be called only once.
def self.load_defaults
each_spec([default_specifications_dir]) do |spec|
# #load returns nil if the spec is bad, so we just ignore
# it at this stage
Gem.register_default_spec(spec)
end
end
##
# Adds +spec+ to the known specifications, keeping the collection
# properly sorted.
def self.add_spec spec
# TODO: find all extraneous adds
# puts
# p :add_spec => [spec.full_name, caller.reject { |s| s =~ /minitest/ }]
# TODO: flush the rest of the crap from the tests
# raise "no dupes #{spec.full_name} in #{all_names.inspect}" if
# _all.include? spec
raise "nil spec!" unless spec # TODO: remove once we're happy with tests
return if _all.include? spec
_all << spec
stubs << spec
_resort!(_all)
_resort!(stubs)
end
##
# Adds multiple specs to the known specifications.
def self.add_specs *specs
raise "nil spec!" if specs.any?(&:nil?) # TODO: remove once we're happy
# TODO: this is much more efficient, but we need the extra checks for now
# _all.concat specs
# _resort!
specs.each do |spec| # TODO: slow
add_spec spec
end
end
##
# Returns all specifications. This method is discouraged from use.
# You probably want to use one of the Enumerable methods instead.
def self.all
warn "NOTE: Specification.all called from #{caller.first}" unless
Gem::Deprecate.skip
_all
end
##
# Sets the known specs to +specs+. Not guaranteed to work for you in
# the future. Use at your own risk. Caveat emptor. Doomy doom doom.
# Etc etc.
#
#--
# Makes +specs+ the known specs
# Listen, time is a river
# Winter comes, code breaks
#
# -- wilsonb
def self.all= specs
@@all = @@stubs = specs
end
##
# Return full names of all specs in sorted order.
def self.all_names
self._all.map(&:full_name)
end
##
# Return the list of all array-oriented instance variables.
#--
# Not sure why we need to use so much stupid reflection in here...
def self.array_attributes
@@array_attributes.dup
end
##
# Return the list of all instance variables.
#--
# Not sure why we need to use so much stupid reflection in here...
def self.attribute_names
@@attributes.dup
end
##
# Return the directories that Specification uses to find specs.
def self.dirs
@@dirs ||= Gem.path.collect { |dir|
File.join dir.dup.untaint, "specifications"
}
end
##
# Set the directories that Specification uses to find specs. Setting
# this resets the list of known specs.
def self.dirs= dirs
self.reset
@@dirs = Array(dirs).map { |dir| File.join dir, "specifications" }
end
extend Enumerable
##
# Enumerate every known spec. See ::dirs= and ::add_spec to set the list of
# specs.
def self.each
return enum_for(:each) unless block_given?
self._all.each do |x|
yield x
end
end
##
# Returns every spec that matches +name+ and optional +requirements+.
def self.find_all_by_name name, *requirements
requirements = Gem::Requirement.default if requirements.empty?
# TODO: maybe try: find_all { |s| spec === dep }
Gem::Dependency.new(name, *requirements).matching_specs
end
##
# Find the best specification matching a +name+ and +requirements+. Raises
# if the dependency doesn't resolve to a valid specification.
def self.find_by_name name, *requirements
requirements = Gem::Requirement.default if requirements.empty?
# TODO: maybe try: find { |s| spec === dep }
Gem::Dependency.new(name, *requirements).to_spec
end
##
# Return the best specification that contains the file matching +path+.
def self.find_by_path path
self.find { |spec|
spec.contains_requirable_file? path
}
end
##
# Return the best specification that contains the file matching +path+
# amongst the specs that are not activated.
def self.find_inactive_by_path path
stub = stubs.find { |s|
s.contains_requirable_file? path unless s.activated?
}
stub && stub.to_spec
end
##
# Return currently unresolved specs that contain the file matching +path+.
def self.find_in_unresolved path
# TODO: do we need these?? Kill it
specs = unresolved_deps.values.map { |dep| dep.to_specs }.flatten
specs.find_all { |spec| spec.contains_requirable_file? path }
end
##
# Search through all unresolved deps and sub-dependencies and return
# specs that contain the file matching +path+.
def self.find_in_unresolved_tree path
specs = unresolved_deps.values.map { |dep| dep.to_specs }.flatten
specs.reverse_each do |spec|
trails = []
spec.traverse do |from_spec, dep, to_spec, trail|
next unless to_spec.conflicts.empty?
trails << trail if to_spec.contains_requirable_file? path
end
next if trails.empty?
return trails.map(&:reverse).sort.first.reverse
end
[]
end
##
# Special loader for YAML files. When a Specification object is loaded
# from a YAML file, it bypasses the normal Ruby object initialization
# routine (#initialize). This method makes up for that and deals with
# gems of different ages.
#
# +input+ can be anything that YAML.load() accepts: String or IO.
def self.from_yaml(input)
Gem.load_yaml
input = normalize_yaml_input input
spec = YAML.load input
if spec && spec.class == FalseClass then
raise Gem::EndOfYAMLException
end
unless Gem::Specification === spec then
raise Gem::Exception, "YAML data doesn't evaluate to gem specification"
end
spec.specification_version ||= NONEXISTENT_SPECIFICATION_VERSION
spec.reset_nil_attributes_to_default
spec
end
##
# Return the latest specs, optionally including prerelease specs if
# +prerelease+ is true.
def self.latest_specs prerelease = false
result = Hash.new { |h,k| h[k] = {} }
native = {}
Gem::Specification.reverse_each do |spec|
next if spec.version.prerelease? unless prerelease
native[spec.name] = spec.version if spec.platform == Gem::Platform::RUBY
result[spec.name][spec.platform] = spec
end
result.map(&:last).map(&:values).flatten.reject { |spec|
minimum = native[spec.name]
minimum && spec.version < minimum
}.sort_by{ |tup| tup.name }
end
##
# Loads Ruby format gemspec from +file+.
def self.load file
return unless file
file = file.dup.untaint
return unless File.file?(file)
spec = LOAD_CACHE[file]
return spec if spec
code = if defined? Encoding
File.read file, :mode => 'r:UTF-8:-'
else
File.read file
end
code.untaint
begin
spec = eval code, binding, file
if Gem::Specification === spec
spec.loaded_from = File.expand_path file.to_s
LOAD_CACHE[file] = spec
return spec
end
warn "[#{file}] isn't a Gem::Specification (#{spec.class} instead)."
rescue SignalException, SystemExit
raise
rescue SyntaxError, Exception => e
warn "Invalid gemspec in [#{file}]: #{e}"
end
nil
end
##
# Specification attributes that must be non-nil
def self.non_nil_attributes
@@non_nil_attributes.dup
end
##
# Make sure the YAML specification is properly formatted with dashes
def self.normalize_yaml_input(input)
result = input.respond_to?(:read) ? input.read : input
result = "--- " + result unless result =~ /\A--- /
result.gsub!(/ !!null \n/, " \n")
# date: 2011-04-26 00:00:00.000000000Z
# date: 2011-04-26 00:00:00.000000000 Z
result.gsub!(/^(date: \d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}\.\d+?)Z/, '\1 Z')
result
end
##
# Return a list of all outdated local gem names. This method is HEAVY
# as it must go fetch specifications from the server.
#
# Use outdated_and_latest_version if you wish to retrieve the latest remote
# version as well.
def self.outdated
outdated_and_latest_version.map { |local, _| local.name }
end
##
# Enumerates the outdated local gems yielding the local specification and
# the latest remote version.
#
# This method may take some time to return as it must check each local gem
# against the server's index.
def self.outdated_and_latest_version
return enum_for __method__ unless block_given?
# TODO: maybe we should switch to rubygems' version service?
fetcher = Gem::SpecFetcher.fetcher
latest_specs(true).each do |local_spec|
dependency =
Gem::Dependency.new local_spec.name, ">= #{local_spec.version}"
remotes, = fetcher.search_for_dependency dependency
remotes = remotes.map { |n, _| n.version }
latest_remote = remotes.sort.last
yield [local_spec, latest_remote] if
latest_remote and local_spec.version < latest_remote
end
nil
end
##
# Removes +spec+ from the known specs.
def self.remove_spec spec
_all.delete spec
stubs.delete_if { |s| s.full_name == spec.full_name }
end
##
# Is +name+ a required attribute?
def self.required_attribute?(name)
@@required_attributes.include? name.to_sym
end
##
# Required specification attributes
def self.required_attributes
@@required_attributes.dup
end
##
# Reset the list of known specs, running pre and post reset hooks
# registered in Gem.
def self.reset
@@dirs = nil
Gem.pre_reset_hooks.each { |hook| hook.call }
@@all = nil
@@stubs = nil
_clear_load_cache
unresolved = unresolved_deps
unless unresolved.empty? then
w = "W" + "ARN"
warn "#{w}: Unresolved specs during Gem::Specification.reset:"
unresolved.values.each do |dep|
warn " #{dep}"
end
warn "#{w}: Clearing out unresolved specs."
warn "Please report a bug if this causes problems."
unresolved.clear
end
Gem.post_reset_hooks.each { |hook| hook.call }
end
# DOC: This method needs documented or nodoc'd
def self.unresolved_deps
@unresolved_deps ||= Hash.new { |h, n| h[n] = Gem::Dependency.new n }
end
##
# Load custom marshal format, re-initializing defaults as needed
def self._load(str)
array = Marshal.load str
spec = Gem::Specification.new
spec.instance_variable_set :@specification_version, array[1]
current_version = CURRENT_SPECIFICATION_VERSION
field_count = if spec.specification_version > current_version then
spec.instance_variable_set :@specification_version,
current_version
MARSHAL_FIELDS[current_version]
else
MARSHAL_FIELDS[spec.specification_version]
end
if array.size < field_count then
raise TypeError, "invalid Gem::Specification format #{array.inspect}"
end
# Cleanup any YAML::PrivateType. They only show up for an old bug
# where nil => null, so just convert them to nil based on the type.
array.map! { |e| e.kind_of?(YAML::PrivateType) ? nil : e }
spec.instance_variable_set :@rubygems_version, array[0]
# spec version
spec.instance_variable_set :@name, array[2]
spec.instance_variable_set :@version, array[3]
spec.date = array[4]
spec.instance_variable_set :@summary, array[5]
spec.instance_variable_set :@required_ruby_version, array[6]
spec.instance_variable_set :@required_rubygems_version, array[7]
spec.instance_variable_set :@original_platform, array[8]
spec.instance_variable_set :@dependencies, array[9]
spec.instance_variable_set :@rubyforge_project, array[10]
spec.instance_variable_set :@email, array[11]
spec.instance_variable_set :@authors, array[12]
spec.instance_variable_set :@description, array[13]
spec.instance_variable_set :@homepage, array[14]
spec.instance_variable_set :@has_rdoc, array[15]
spec.instance_variable_set :@new_platform, array[16]
spec.instance_variable_set :@platform, array[16].to_s
spec.instance_variable_set :@license, array[17]
spec.instance_variable_set :@metadata, array[18]
spec.instance_variable_set :@loaded, false
spec.instance_variable_set :@activated, false
spec
end
def <=>(other) # :nodoc:
sort_obj <=> other.sort_obj
end
def == other # :nodoc:
self.class === other &&
name == other.name &&
version == other.version &&
platform == other.platform
end
##
# Dump only crucial instance variables.
#--
# MAINTAIN ORDER!
# (down with the man)
def _dump(limit)
Marshal.dump [
@rubygems_version,
@specification_version,
@name,
@version,
date,
@summary,
@required_ruby_version,
@required_rubygems_version,
@original_platform,
@dependencies,
@rubyforge_project,
@email,
@authors,
@description,
@homepage,
true, # has_rdoc
@new_platform,
@licenses,
@metadata
]
end
##
# Activate this spec, registering it as a loaded spec and adding
# it's lib paths to $LOAD_PATH. Returns true if the spec was
# activated, false if it was previously activated. Freaks out if
# there are conflicts upon activation.
def activate
other = Gem.loaded_specs[self.name]
if other then
check_version_conflict other
return false
end
raise_if_conflicts
activate_dependencies
add_self_to_load_path
Gem.loaded_specs[self.name] = self
@activated = true
@loaded = true
return true
end
##
# Activate all unambiguously resolved runtime dependencies of this
# spec. Add any ambiguous dependencies to the unresolved list to be
# resolved later, as needed.
def activate_dependencies
unresolved = Gem::Specification.unresolved_deps
self.runtime_dependencies.each do |spec_dep|
if loaded = Gem.loaded_specs[spec_dep.name]
next if spec_dep.matches_spec? loaded
msg = "can't satisfy '#{spec_dep}', already activated '#{loaded.full_name}'"
e = Gem::LoadError.new msg
e.name = spec_dep.name
raise e
end
specs = spec_dep.to_specs
if specs.size == 1 then
specs.first.activate
else
name = spec_dep.name
unresolved[name] = unresolved[name].merge spec_dep
end
end
unresolved.delete self.name
end
##
# Returns an array with bindir attached to each executable in the
# +executables+ list
def add_bindir(executables)
return nil if executables.nil?
if @bindir then
Array(executables).map { |e| File.join(@bindir, e) }
else
executables
end
rescue
return nil
end
##
# Adds a dependency on gem +dependency+ with type +type+ that requires
# +requirements+. Valid types are currently <tt>:runtime</tt> and
# <tt>:development</tt>.
def add_dependency_with_type(dependency, type, *requirements)
requirements = if requirements.empty? then
Gem::Requirement.default
else
requirements.flatten
end
unless dependency.respond_to?(:name) &&
dependency.respond_to?(:version_requirements)
dependency = Gem::Dependency.new(dependency.to_s, requirements, type)
end
dependencies << dependency
end
private :add_dependency_with_type
alias add_dependency add_runtime_dependency
##
# Adds this spec's require paths to LOAD_PATH, in the proper location.
def add_self_to_load_path
return if default_gem?
paths = full_require_paths
# gem directories must come after -I and ENV['RUBYLIB']
insert_index = Gem.load_path_insert_index
if insert_index then
# gem directories must come after -I and ENV['RUBYLIB']
$LOAD_PATH.insert(insert_index, *paths)
else
# we are probably testing in core, -I and RUBYLIB don't apply
$LOAD_PATH.unshift(*paths)
end
end
##
# Singular reader for #authors. Returns the first author in the list
def author
val = authors and val.first
end
##
# The list of author names who wrote this gem.
#
# spec.authors = ['Chad Fowler', 'Jim Weirich', 'Rich Kilmer']
def authors
@authors ||= []
end
##
# Returns the full path to installed gem's bin directory.
#
# NOTE: do not confuse this with +bindir+, which is just 'bin', not
# a full path.
def bin_dir
@bin_dir ||= File.join gem_dir, bindir # TODO: this is unfortunate
end
##
# Returns the full path to an executable named +name+ in this gem.
def bin_file name
File.join bin_dir, name
end
##
# Returns the build_args used to install the gem
def build_args
if File.exist? build_info_file
build_info = File.readlines build_info_file
build_info = build_info.map { |x| x.strip }
build_info.delete ""
build_info
else
[]
end
end
##
# Builds extensions for this platform if the gem has extensions listed and
# the gem.build_complete file is missing.
def build_extensions # :nodoc:
return if default_gem?
return if extensions.empty?
return if installed_by_version < Gem::Version.new('2.2.0.preview.2')
return if File.exist? gem_build_complete_path
return if !File.writable?(base_dir)
return if !File.exist?(File.join(base_dir, 'extensions'))
begin
# We need to require things in $LOAD_PATH without looking for the
# extension we are about to build.
unresolved_deps = Gem::Specification.unresolved_deps.dup
Gem::Specification.unresolved_deps.clear
require 'rubygems/config_file'
require 'rubygems/ext'
require 'rubygems/user_interaction'
ui = Gem::SilentUI.new
Gem::DefaultUserInteraction.use_ui ui do
builder = Gem::Ext::Builder.new self
builder.build_extensions
end
ensure
ui.close if ui
Gem::Specification.unresolved_deps.replace unresolved_deps
end
end
##
# Returns the full path to the build info directory
def build_info_dir
File.join base_dir, "build_info"
end
##
# Returns the full path to the file containing the build
# information generated when the gem was installed
def build_info_file
File.join build_info_dir, "#{full_name}.info"
end
##
# Returns the full path to the cache directory containing this
# spec's cached gem.
def cache_dir
@cache_dir ||= File.join base_dir, "cache"
end
##
# Returns the full path to the cached gem for this spec.
def cache_file
@cache_file ||= File.join cache_dir, "#{full_name}.gem"
end
##
# Return any possible conflicts against the currently loaded specs.
def conflicts
conflicts = {}
self.runtime_dependencies.each { |dep|
spec = Gem.loaded_specs[dep.name]
if spec and not spec.satisfies_requirement? dep
(conflicts[spec] ||= []) << dep
end
}
conflicts
end
##
# The date this gem was created. Lazily defaults to the current UTC date.
#
# There is no need to set this in your gem specification.
def date
@date ||= TODAY
end
DateLike = Object.new # :nodoc:
def DateLike.===(obj) # :nodoc:
defined?(::Date) and Date === obj
end
DateTimeFormat = # :nodoc:
/\A
(\d{4})-(\d{2})-(\d{2})
(\s+ \d{2}:\d{2}:\d{2}\.\d+ \s* (Z | [-+]\d\d:\d\d) )?
\Z/x
##
# The date this gem was created
#
# DO NOT set this, it is set automatically when the gem is packaged.
def date= date
# We want to end up with a Time object with one-day resolution.
# This is the cleanest, most-readable, faster-than-using-Date
# way to do it.
@date = case date
when String then
if DateTimeFormat =~ date then
Time.utc($1.to_i, $2.to_i, $3.to_i)
# Workaround for where the date format output from psych isn't
# parsed as a Time object by syck and thus comes through as a
# string.
elsif /\A(\d{4})-(\d{2})-(\d{2}) \d{2}:\d{2}:\d{2}\.\d+?Z\z/ =~ date then
Time.utc($1.to_i, $2.to_i, $3.to_i)
else
raise(Gem::InvalidSpecificationException,
"invalid date format in specification: #{date.inspect}")
end
when Time, DateLike then
Time.utc(date.year, date.month, date.day)
else
TODAY
end
end
##
# The default executable for this gem.
#
# Deprecated: The name of the gem is assumed to be the name of the
# executable now. See Gem.bin_path.
def default_executable # :nodoc:
if defined?(@default_executable) and @default_executable
result = @default_executable
elsif @executables and @executables.size == 1
result = Array(@executables).first
else
result = nil
end
result
end
##
# The default value for specification attribute +name+
def default_value name
@@default_value[name]
end
##
# A list of Gem::Dependency objects this gem depends on.
#
# Use #add_dependency or #add_development_dependency to add dependencies to
# a gem.
def dependencies
@dependencies ||= []
end
##
# Return a list of all gems that have a dependency on this gemspec. The
# list is structured with entries that conform to:
#
# [depending_gem, dependency, [list_of_gems_that_satisfy_dependency]]
def dependent_gems
out = []
Gem::Specification.each do |spec|
spec.dependencies.each do |dep|
if self.satisfies_requirement?(dep) then
sats = []
find_all_satisfiers(dep) do |sat|
sats << sat
end
out << [spec, dep, sats]
end
end
end
out
end
##
# Returns all specs that matches this spec's runtime dependencies.
def dependent_specs
runtime_dependencies.map { |dep| dep.to_specs }.flatten
end
##
# A detailed description of this gem. See also #summary
def description= str
@description = str.to_s
end
##
# List of dependencies that are used for development
def development_dependencies
dependencies.select { |d| d.type == :development }
end
##
# Returns the full path to this spec's documentation directory. If +type+
# is given it will be appended to the end. For example:
#
# spec.doc_dir # => "/path/to/gem_repo/doc/a-1"
#
# spec.doc_dir 'ri' # => "/path/to/gem_repo/doc/a-1/ri"
def doc_dir type = nil
@doc_dir ||= File.join base_dir, 'doc', full_name
if type then
File.join @doc_dir, type
else
@doc_dir
end
end
def encode_with coder # :nodoc:
mark_version
coder.add 'name', @name
coder.add 'version', @version
platform = case @original_platform
when nil, '' then
'ruby'
when String then
@original_platform
else
@original_platform.to_s
end
coder.add 'platform', platform
attributes = @@attributes.map(&:to_s) - %w[name version platform]
attributes.each do |name|
coder.add name, instance_variable_get("@#{name}")
end
end
def eql? other # :nodoc:
self.class === other && same_attributes?(other)
end
##
# Singular accessor for #executables
def executable
val = executables and val.first
end
##
# Singular accessor for #executables
def executable=o
self.executables = [o]
end
##
# Sets executables to +value+, ensuring it is an array. Don't
# use this, push onto the array instead.
def executables= value
# TODO: warn about setting instead of pushing
@executables = Array(value)
end
##
# Sets extensions to +extensions+, ensuring it is an array. Don't
# use this, push onto the array instead.
def extensions= extensions
# TODO: warn about setting instead of pushing
@extensions = Array extensions
end
##
# Sets extra_rdoc_files to +files+, ensuring it is an array. Don't
# use this, push onto the array instead.
def extra_rdoc_files= files
# TODO: warn about setting instead of pushing
@extra_rdoc_files = Array files
end
##
# The default (generated) file name of the gem. See also #spec_name.
#
# spec.file_name # => "example-1.0.gem"
def file_name
"#{full_name}.gem"
end
##
# Sets files to +files+, ensuring it is an array.
def files= files
@files = Array files
end
##
# Finds all gems that satisfy +dep+
def find_all_satisfiers dep
Gem::Specification.each do |spec|
yield spec if spec.satisfies_requirement? dep
end
end
private :find_all_satisfiers
##
# Creates a duplicate spec without large blobs that aren't used at runtime.
def for_cache
spec = dup
spec.files = nil
spec.test_files = nil
spec
end
def find_full_gem_path # :nodoc:
super || File.expand_path(File.join(gems_dir, original_name))
end
private :find_full_gem_path
def full_name
@full_name ||= super
end
##
# The path to the gem.build_complete file within the extension install
# directory.
def gem_build_complete_path # :nodoc:
File.join extension_dir, 'gem.build_complete'
end
##
# Work around bundler removing my methods
def gem_dir # :nodoc:
super
end
##
# Deprecated and ignored, defaults to true.
#
# Formerly used to indicate this gem was RDoc-capable.
def has_rdoc # :nodoc:
true
end
##
# Deprecated and ignored.
#
# Formerly used to indicate this gem was RDoc-capable.
def has_rdoc= ignored # :nodoc:
@has_rdoc = true
end
alias :has_rdoc? :has_rdoc # :nodoc:
##
# True if this gem has files in test_files
def has_unit_tests? # :nodoc:
not test_files.empty?
end
# :stopdoc:
alias has_test_suite? has_unit_tests?
# :startdoc:
def hash # :nodoc:
name.hash ^ version.hash
end
def init_with coder # :nodoc:
@installed_by_version ||= nil
yaml_initialize coder.tag, coder.map
end
##
# Specification constructor. Assigns the default values to the attributes
# and yields itself for further initialization. Optionally takes +name+ and
# +version+.
def initialize name = nil, version = nil
@loaded = false
@activated = false
self.loaded_from = nil
@original_platform = nil
@installed_by_version = nil
@@nil_attributes.each do |key|
instance_variable_set "@#{key}", nil
end
@@non_nil_attributes.each do |key|
default = default_value(key)
value = Dupable[key] ? default.dup : default
instance_variable_set "@#{key}", value
end
@new_platform = Gem::Platform::RUBY
self.name = name if name
self.version = version if version
yield self if block_given?
end
##
# Duplicates array_attributes from +other_spec+ so state isn't shared.
def initialize_copy other_spec
self.class.array_attributes.each do |name|
name = :"@#{name}"
next unless other_spec.instance_variable_defined? name
begin
val = other_spec.instance_variable_get(name)
if val then
instance_variable_set name, val.dup
elsif Gem.configuration.really_verbose
warn "WARNING: #{full_name} has an invalid nil value for #{name}"
end
rescue TypeError
e = Gem::FormatException.new \
"#{full_name} has an invalid value for #{name}"
e.file_path = loaded_from
raise e
end
end
end
##
# Expire memoized instance variables that can incorrectly generate, replace
# or miss files due changes in certain attributes used to compute them.
def invalidate_memoized_attributes
@full_name = nil
@cache_file = nil
end
private :invalidate_memoized_attributes
def inspect # :nodoc:
if $DEBUG
super
else
"#<#{self.class}:0x#{__id__.to_s(16)} #{full_name}>"
end
end
##
# Returns a string usable in Dir.glob to match all requirable paths
# for this spec.
def lib_dirs_glob
dirs = if self.require_paths.size > 1 then
"{#{self.require_paths.join(',')}}"
else
self.require_paths.first
end
"#{self.full_gem_path}/#{dirs}"
end
##
# Files in the Gem under one of the require_paths
def lib_files
@files.select do |file|
require_paths.any? do |path|
file.start_with? path
end
end
end
##
# Singular accessor for #licenses
def license
val = licenses and val.first
end
##
# Plural accessor for setting licenses
#
# See #license= for details
def licenses
@licenses ||= []
end
def loaded_from= path # :nodoc:
super
@bin_dir = nil
@cache_dir = nil
@cache_file = nil
@doc_dir = nil
@ri_dir = nil
@spec_dir = nil
@spec_file = nil
end
##
# Sets the rubygems_version to the current RubyGems version.
def mark_version
@rubygems_version = Gem::VERSION
end
##
# Return all files in this gem that match for +glob+.
def matches_for_glob glob # TODO: rename?
# TODO: do we need these?? Kill it
glob = File.join(self.lib_dirs_glob, glob)
Dir[glob].map { |f| f.untaint } # FIX our tests are broken, run w/ SAFE=1
end
##
# Warn about unknown attributes while loading a spec.
def method_missing(sym, *a, &b) # :nodoc:
if @specification_version > CURRENT_SPECIFICATION_VERSION and
sym.to_s =~ /=$/ then
warn "ignoring #{sym} loading #{full_name}" if $DEBUG
else
super
end
end
##
# Is this specification missing its extensions? When this returns true you
# probably want to build_extensions
def missing_extensions?
return false if default_gem?
return false if extensions.empty?
return false if installed_by_version < Gem::Version.new('2.2.0.preview.2')
return false if File.exist? gem_build_complete_path
true
end
##
# Normalize the list of files so that:
# * All file lists have redundancies removed.
# * Files referenced in the extra_rdoc_files are included in the package
# file list.
def normalize
if defined?(@extra_rdoc_files) and @extra_rdoc_files then
@extra_rdoc_files.uniq!
@files ||= []
@files.concat(@extra_rdoc_files)
end
@files = @files.uniq if @files
@extensions = @extensions.uniq if @extensions
@test_files = @test_files.uniq if @test_files
@executables = @executables.uniq if @executables
@extra_rdoc_files = @extra_rdoc_files.uniq if @extra_rdoc_files
end
##
# Return a NameTuple that represents this Specification
def name_tuple
Gem::NameTuple.new name, version, original_platform
end
##
# Returns the full name (name-version) of this gemspec using the original
# platform. For use with legacy gems.
def original_name # :nodoc:
if platform == Gem::Platform::RUBY or platform.nil? then
"#{@name}-#{@version}"
else
"#{@name}-#{@version}-#{@original_platform}"
end
end
##
# Cruft. Use +platform+.
def original_platform # :nodoc:
@original_platform ||= platform
end
##
# The platform this gem runs on. See Gem::Platform for details.
def platform
@new_platform ||= Gem::Platform::RUBY
end
def pretty_print(q) # :nodoc:
q.group 2, 'Gem::Specification.new do |s|', 'end' do
q.breakable
attributes = @@attributes - [:name, :version]
attributes.unshift :installed_by_version
attributes.unshift :version
attributes.unshift :name
attributes.each do |attr_name|
current_value = self.send attr_name
if current_value != default_value(attr_name) or
self.class.required_attribute? attr_name then
q.text "s.#{attr_name} = "
if attr_name == :date then
current_value = current_value.utc
q.text "Time.utc(#{current_value.year}, #{current_value.month}, #{current_value.day})"
else
q.pp current_value
end
q.breakable
end
end
end
end
##
# Raise an exception if the version of this spec conflicts with the one
# that is already loaded (+other+)
def check_version_conflict other # :nodoc:
return if self.version == other.version
# This gem is already loaded. If the currently loaded gem is not in the
# list of candidate gems, then we have a version conflict.
msg = "can't activate #{full_name}, already activated #{other.full_name}"
e = Gem::LoadError.new msg
e.name = self.name
# TODO: e.requirement = dep.requirement
raise e
end
private :check_version_conflict
##
# Check the spec for possible conflicts and freak out if there are any.
def raise_if_conflicts # :nodoc:
conf = self.conflicts
unless conf.empty? then
raise Gem::ConflictError.new self, conf
end
end
##
# Sets rdoc_options to +value+, ensuring it is an array. Don't
# use this, push onto the array instead.
def rdoc_options= options
# TODO: warn about setting instead of pushing
@rdoc_options = Array options
end
##
# Singular accessor for #require_paths
def require_path
val = require_paths and val.first
end
##
# Singular accessor for #require_paths
def require_path= path
self.require_paths = Array(path)
end
##
# Set requirements to +req+, ensuring it is an array. Don't
# use this, push onto the array instead.
def requirements= req
# TODO: warn about setting instead of pushing
@requirements = Array req
end
def respond_to_missing? m, include_private = false # :nodoc:
false
end
##
# Returns the full path to this spec's ri directory.
def ri_dir
@ri_dir ||= File.join base_dir, 'ri', full_name
end
##
# Return a string containing a Ruby code representation of the given
# object.
def ruby_code(obj)
case obj
when String then obj.dump
when Array then '[' + obj.map { |x| ruby_code x }.join(", ") + ']'
when Hash then
seg = obj.keys.sort.map { |k| "#{k.to_s.dump} => #{obj[k].to_s.dump}" }
"{ #{seg.join(', ')} }"
when Gem::Version then obj.to_s.dump
when DateLike then obj.strftime('%Y-%m-%d').dump
when Time then obj.strftime('%Y-%m-%d').dump
when Numeric then obj.inspect
when true, false, nil then obj.inspect
when Gem::Platform then "Gem::Platform.new(#{obj.to_a.inspect})"
when Gem::Requirement then
list = obj.as_list
"Gem::Requirement.new(#{ruby_code(list.size == 1 ? obj.to_s : list)})"
else raise Gem::Exception, "ruby_code case not handled: #{obj.class}"
end
end
private :ruby_code
##
# List of dependencies that will automatically be activated at runtime.
def runtime_dependencies
dependencies.select { |d| d.type == :runtime }
end
##
# True if this gem has the same attributes as +other+.
def same_attributes? spec
@@attributes.all? { |name, default| self.send(name) == spec.send(name) }
end
private :same_attributes?
##
# Checks if this specification meets the requirement of +dependency+.
def satisfies_requirement? dependency
return @name == dependency.name &&
dependency.requirement.satisfied_by?(@version)
end
##
# Returns an object you can use to sort specifications in #sort_by.
def sort_obj
[@name, @version, @new_platform == Gem::Platform::RUBY ? -1 : 1]
end
##
# Used by Gem::Resolver to order Gem::Specification objects
def source # :nodoc:
Gem::Source::Installed.new
end
##
# Returns the full path to the directory containing this spec's
# gemspec file. eg: /usr/local/lib/ruby/gems/1.8/specifications
def spec_dir
@spec_dir ||= File.join base_dir, "specifications"
end
##
# Returns the full path to this spec's gemspec file.
# eg: /usr/local/lib/ruby/gems/1.8/specifications/mygem-1.0.gemspec
def spec_file
@spec_file ||= File.join spec_dir, "#{full_name}.gemspec"
end
##
# The default name of the gemspec. See also #file_name
#
# spec.spec_name # => "example-1.0.gemspec"
def spec_name
"#{full_name}.gemspec"
end
##
# A short summary of this gem's description.
def summary= str
@summary = str.to_s.strip.
gsub(/(\w-)\n[ \t]*(\w)/, '\1\2').gsub(/\n[ \t]*/, " ") # so. weird.
end
##
# Singular accessor for #test_files
def test_file # :nodoc:
val = test_files and val.first
end
##
# Singular mutator for #test_files
def test_file= file # :nodoc:
self.test_files = [file]
end
##
# Test files included in this gem. You cannot append to this accessor, you
# must assign to it.
def test_files # :nodoc:
# Handle the possibility that we have @test_suite_file but not
# @test_files. This will happen when an old gem is loaded via
# YAML.
if defined? @test_suite_file then
@test_files = [@test_suite_file].flatten
@test_suite_file = nil
end
if defined?(@test_files) and @test_files then
@test_files
else
@test_files = []
end
end
##
# Returns a Ruby code representation of this specification, such that it can
# be eval'ed and reconstruct the same specification later. Attributes that
# still have their default values are omitted.
def to_ruby
mark_version
result = []
result << "# -*- encoding: utf-8 -*-"
result << "#{Gem::StubSpecification::PREFIX}#{name} #{version} #{platform} #{raw_require_paths.join("\0")}"
result << "#{Gem::StubSpecification::PREFIX}#{extensions.join "\0"}" unless
extensions.empty?
result << nil
result << "Gem::Specification.new do |s|"
result << " s.name = #{ruby_code name}"
result << " s.version = #{ruby_code version}"
unless platform.nil? or platform == Gem::Platform::RUBY then
result << " s.platform = #{ruby_code original_platform}"
end
result << ""
result << " s.required_rubygems_version = #{ruby_code required_rubygems_version} if s.respond_to? :required_rubygems_version="
if metadata and !metadata.empty?
result << " s.metadata = #{ruby_code metadata} if s.respond_to? :metadata="
end
result << " s.require_paths = #{ruby_code raw_require_paths}"
handled = [
:dependencies,
:name,
:platform,
:require_paths,
:required_rubygems_version,
:specification_version,
:version,
:has_rdoc,
:default_executable,
:metadata
]
@@attributes.each do |attr_name|
next if handled.include? attr_name
current_value = self.send(attr_name)
if current_value != default_value(attr_name) or
self.class.required_attribute? attr_name then
result << " s.#{attr_name} = #{ruby_code current_value}"
end
end
if @installed_by_version then
result << nil
result << " s.installed_by_version = \"#{Gem::VERSION}\" if s.respond_to? :installed_by_version"
end
unless dependencies.empty? then
result << nil
result << " if s.respond_to? :specification_version then"
result << " s.specification_version = #{specification_version}"
result << nil
result << " if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then"
dependencies.each do |dep|
req = dep.requirements_list.inspect
dep.instance_variable_set :@type, :runtime if dep.type.nil? # HACK
result << " s.add_#{dep.type}_dependency(%q<#{dep.name}>, #{req})"
end
result << " else"
dependencies.each do |dep|
version_reqs_param = dep.requirements_list.inspect
result << " s.add_dependency(%q<#{dep.name}>, #{version_reqs_param})"
end
result << ' end'
result << " else"
dependencies.each do |dep|
version_reqs_param = dep.requirements_list.inspect
result << " s.add_dependency(%q<#{dep.name}>, #{version_reqs_param})"
end
result << " end"
end
result << "end"
result << nil
result.join "\n"
end
##
# Returns a Ruby lighter-weight code representation of this specification,
# used for indexing only.
#
# See #to_ruby.
def to_ruby_for_cache
for_cache.to_ruby
end
def to_s # :nodoc:
"#<Gem::Specification name=#{@name} version=#{@version}>"
end
##
# Returns self
def to_spec
self
end
def to_yaml(opts = {}) # :nodoc:
if (YAML.const_defined?(:ENGINE) && !YAML::ENGINE.syck?) ||
(defined?(Psych) && YAML == Psych) then
# Because the user can switch the YAML engine behind our
# back, we have to check again here to make sure that our
# psych code was properly loaded, and load it if not.
unless Gem.const_defined?(:NoAliasYAMLTree)
require 'rubygems/psych_tree'
end
builder = Gem::NoAliasYAMLTree.create
builder << self
ast = builder.tree
io = Gem::StringSink.new
io.set_encoding Encoding::UTF_8 if Object.const_defined? :Encoding
Psych::Visitors::Emitter.new(io).accept(ast)
io.string.gsub(/ !!null \n/, " \n")
else
YAML.quick_emit object_id, opts do |out|
out.map taguri, to_yaml_style do |map|
encode_with map
end
end
end
end
##
# Recursively walk dependencies of this spec, executing the +block+ for each
# hop.
def traverse trail = [], &block
trail = trail + [self]
runtime_dependencies.each do |dep|
dep.to_specs.each do |dep_spec|
block[self, dep, dep_spec, trail + [dep_spec]]
dep_spec.traverse(trail, &block) unless
trail.map(&:name).include? dep_spec.name
end
end
end
##
# Checks that the specification contains all required fields, and does a
# very basic sanity check.
#
# Raises InvalidSpecificationException if the spec does not pass the
# checks..
def validate packaging = true
@warnings = 0
require 'rubygems/user_interaction'
extend Gem::UserInteraction
normalize
nil_attributes = self.class.non_nil_attributes.find_all do |name|
instance_variable_get("@#{name}").nil?
end
unless nil_attributes.empty? then
raise Gem::InvalidSpecificationException,
"#{nil_attributes.join ', '} must not be nil"
end
if packaging and rubygems_version != Gem::VERSION then
raise Gem::InvalidSpecificationException,
"expected RubyGems version #{Gem::VERSION}, was #{rubygems_version}"
end
@@required_attributes.each do |symbol|
unless self.send symbol then
raise Gem::InvalidSpecificationException,
"missing value for attribute #{symbol}"
end
end
unless String === name then
raise Gem::InvalidSpecificationException,
"invalid value for attribute name: \"#{name.inspect}\""
end
if raw_require_paths.empty? then
raise Gem::InvalidSpecificationException,
'specification must have at least one require_path'
end
@files.delete_if { |x| File.directory?(x) }
@test_files.delete_if { |x| File.directory?(x) }
@executables.delete_if { |x| File.directory?(File.join(@bindir, x)) }
@extra_rdoc_files.delete_if { |x| File.directory?(x) }
@extensions.delete_if { |x| File.directory?(x) }
non_files = files.reject { |x| File.file?(x) }
unless not packaging or non_files.empty? then
raise Gem::InvalidSpecificationException,
"[\"#{non_files.join "\", \""}\"] are not files"
end
if files.include? file_name then
raise Gem::InvalidSpecificationException,
"#{full_name} contains itself (#{file_name}), check your files list"
end
unless specification_version.is_a?(Fixnum)
raise Gem::InvalidSpecificationException,
'specification_version must be a Fixnum (did you mean version?)'
end
case platform
when Gem::Platform, Gem::Platform::RUBY then # ok
else
raise Gem::InvalidSpecificationException,
"invalid platform #{platform.inspect}, see Gem::Platform"
end
self.class.array_attributes.each do |field|
val = self.send field
klass = case field
when :dependencies
Gem::Dependency
else
String
end
unless Array === val and val.all? { |x| x.kind_of?(klass) } then
raise(Gem::InvalidSpecificationException,
"#{field} must be an Array of #{klass}")
end
end
[:authors].each do |field|
val = self.send field
raise Gem::InvalidSpecificationException, "#{field} may not be empty" if
val.empty?
end
unless Hash === metadata
raise Gem::InvalidSpecificationException,
'metadata must be a hash'
end
metadata.keys.each do |k|
if !k.kind_of?(String)
raise Gem::InvalidSpecificationException,
'metadata keys must be a String'
end
if k.size > 128
raise Gem::InvalidSpecificationException,
"metadata key too large (#{k.size} > 128)"
end
end
metadata.values.each do |k|
if !k.kind_of?(String)
raise Gem::InvalidSpecificationException,
'metadata values must be a String'
end
if k.size > 1024
raise Gem::InvalidSpecificationException,
"metadata value too large (#{k.size} > 1024)"
end
end
licenses.each { |license|
if license.length > 64
raise Gem::InvalidSpecificationException,
"each license must be 64 characters or less"
end
}
warning <<-warning if licenses.empty?
licenses is empty, but is recommended. Use a license abbreviation from:
http://opensource.org/licenses/alphabetical
warning
validate_permissions
# reject lazy developers:
lazy = '"FIxxxXME" or "TOxxxDO"'.gsub(/xxx/, '')
unless authors.grep(/FI XME|TO DO/x).empty? then
raise Gem::InvalidSpecificationException, "#{lazy} is not an author"
end
unless Array(email).grep(/FI XME|TO DO/x).empty? then
raise Gem::InvalidSpecificationException, "#{lazy} is not an email"
end
if description =~ /FI XME|TO DO/x then
raise Gem::InvalidSpecificationException, "#{lazy} is not a description"
end
if summary =~ /FI XME|TO DO/x then
raise Gem::InvalidSpecificationException, "#{lazy} is not a summary"
end
if homepage and not homepage.empty? and
homepage !~ /\A[a-z][a-z\d+.-]*:/i then
raise Gem::InvalidSpecificationException,
"\"#{homepage}\" is not a URI"
end
# Warnings
%w[author description email homepage summary].each do |attribute|
value = self.send attribute
warning "no #{attribute} specified" if value.nil? or value.empty?
end
if description == summary then
warning 'description and summary are identical'
end
# TODO: raise at some given date
warning "deprecated autorequire specified" if autorequire
executables.each do |executable|
executable_path = File.join(bindir, executable)
shebang = File.read(executable_path, 2) == '#!'
warning "#{executable_path} is missing #! line" unless shebang
end
validate_dependencies
true
ensure
if $! or @warnings > 0 then
alert_warning "See http://guides.rubygems.org/specification-reference/ for help"
end
end
##
# Checks that dependencies use requirements as we recommend. Warnings are
# issued when dependencies are open-ended or overly strict for semantic
# versioning.
def validate_dependencies # :nodoc:
seen = {}
dependencies.each do |dep|
if prev = seen[dep.name] then
raise Gem::InvalidSpecificationException, <<-MESSAGE
duplicate dependency on #{dep}, (#{prev.requirement}) use:
add_runtime_dependency '#{dep.name}', '#{dep.requirement}', '#{prev.requirement}'
MESSAGE
end
seen[dep.name] = dep
prerelease_dep = dep.requirements_list.any? do |req|
Gem::Requirement.new(req).prerelease?
end
warning "prerelease dependency on #{dep} is not recommended" if
prerelease_dep
overly_strict = dep.requirement.requirements.length == 1 &&
dep.requirement.requirements.any? do |op, version|
op == '~>' and
not version.prerelease? and
version.segments.length > 2 and
version.segments.first != 0
end
if overly_strict then
_, dep_version = dep.requirement.requirements.first
base = dep_version.segments.first 2
warning <<-WARNING
pessimistic dependency on #{dep} may be overly strict
if #{dep.name} is semantically versioned, use:
add_#{dep.type}_dependency '#{dep.name}', '~> #{base.join '.'}', '>= #{dep_version}'
WARNING
end
open_ended = dep.requirement.requirements.all? do |op, version|
not version.prerelease? and (op == '>' or op == '>=')
end
if open_ended then
op, dep_version = dep.requirement.requirements.first
base = dep_version.segments.first 2
bugfix = if op == '>' then
", '> #{dep_version}'"
elsif op == '>=' and base != dep_version.segments then
", '>= #{dep_version}'"
end
warning <<-WARNING
open-ended dependency on #{dep} is not recommended
if #{dep.name} is semantically versioned, use:
add_#{dep.type}_dependency '#{dep.name}', '~> #{base.join '.'}'#{bugfix}
WARNING
end
end
end
##
# Checks to see if the files to be packaged are world-readable.
def validate_permissions
return if Gem.win_platform?
files.each do |file|
next if File.stat(file).mode & 0444 == 0444
warning "#{file} is not world-readable"
end
executables.each do |name|
exec = File.join @bindir, name
next if File.stat(exec).executable?
warning "#{exec} is not executable"
end
end
##
# Set the version to +version+, potentially also setting
# required_rubygems_version if +version+ indicates it is a
# prerelease.
def version= version
@version = Gem::Version.create(version)
self.required_rubygems_version = '> 1.3.1' if @version.prerelease?
invalidate_memoized_attributes
return @version
end
def stubbed?
false
end
def yaml_initialize(tag, vals) # :nodoc:
vals.each do |ivar, val|
case ivar
when "date"
# Force Date to go through the extra coerce logic in date=
self.date = val.untaint
else
instance_variable_set "@#{ivar}", val.untaint
end
end
@original_platform = @platform # for backwards compatibility
self.platform = Gem::Platform.new @platform
end
##
# Reset nil attributes to their default values to make the spec valid
def reset_nil_attributes_to_default
nil_attributes = self.class.non_nil_attributes.find_all do |name|
!instance_variable_defined?("@#{name}") || instance_variable_get("@#{name}").nil?
end
nil_attributes.each do |attribute|
default = self.default_value attribute
value = case default
when Time, Numeric, Symbol, true, false, nil then default
else default.dup
end
instance_variable_set "@#{attribute}", value
end
@installed_by_version ||= nil
end
def warning statement # :nodoc:
@warnings += 1
alert_warning statement
end
extend Gem::Deprecate
# TODO:
# deprecate :has_rdoc, :none, 2011, 10
# deprecate :has_rdoc?, :none, 2011, 10
# deprecate :has_rdoc=, :none, 2011, 10
# deprecate :default_executable, :none, 2011, 10
# deprecate :default_executable=, :none, 2011, 10
# deprecate :file_name, :cache_file, 2011, 10
# deprecate :full_gem_path, :cache_file, 2011, 10
end
# DOC: What is this and why is it here, randomly, at the end of this file?
Gem.clear_paths
| 26.344791 | 131 | 0.636061 |
ede3382868ac0e5c64e84096a312ff8fadf7f04c | 156 | class UserChannel < ApplicationCable::Channel
def subscribed
stream_for current_user.id
# or
# stream_from "room_#{params[:room]}"
end
end
| 17.333333 | 45 | 0.705128 |
ff506699cc64ae88ca7fad54313dedbd26af193f | 34,589 | # frozen_string_literal: true
require 'packetfu'
require 'packetfu/protos/arp'
require 'packetfu/protos/eth'
require 'packetfu/protos/hsrp'
require 'packetfu/protos/icmp'
require 'packetfu/protos/ip'
require 'packetfu/protos/ipv6'
require 'packetfu/protos/lldp'
require 'packetfu/protos/tcp'
require 'packetfu/protos/udp'
require 'socket'
module PWN
module Plugins
# This plugin is used for interacting with PCAP files to map out and visualize in an
# automated fashion what comprises a infrastructure, network, and/or application
module Packet
# Supported Method Parameters::
# pcap = PWN::Plugins::Packet.open_pcap_file(
# path: 'required - path to packet capture file'
# )
public_class_method def self.open_pcap_file(opts = {})
path = opts[:path].to_s.scrub.strip.chomp if File.exist?(opts[:path].to_s.scrub.strip.chomp)
PacketFu::PcapFile.read_packets(path)
rescue StandardError => e
raise e
end
# Supported Method Parameters::
# pkt = PWN::Plugins::Packet.construct_arp(
# ip_saddr: 'required - source ip of packet',
# ip_daddr: 'required - destination ip to send packet',
# payload: 'optional - packet payload defaults to empty string',
# ip_id: 'optional - defaults to 0xfeed',
# iface: 'optional - interface to send packet (defaults to eth0)',
# )
public_class_method def self.construct_arp(opts = {})
# Ethernet Header
eth_src = opts[:eth_src]
eth_dst = opts[:eth_dst]
if opts[:eth_proto]
eth_proto = opts[:eth_proto]
else
eth_proto = 0x0806 # ARP
end
# ARP Header
if opts[:arp_hw]
arp_hw = opts[:arp_hw].to_i
else
arp_hw = 1
end
if opts[:arp_proto]
arp_proto = opts[:arp_proto]
else
arp_proto = 0x0800 # IPv4
end
if opts[:arp_hw_len]
arp_hw_len = opts[:arp_hw_len].to_i
else
arp_hw_len = 6
end
if opts[:arp_proto_len]
arp_proto_len = opts[:arp_proto_len].to_i
else
arp_proto_len = 4
end
if opts[:arp_opcode]
arp_opcode = opts[:arp_opcode].to_i
else
arp_opcode = 1
end
arp_src_mac = opts[:arp_src_mac]
arp_ip_saddr = opts[:ip_saddr].to_s.scrub.strip.chomp
arp_dst_mac = opts[:arp_dst_mac]
arp_ip_daddr = opts[:ip_daddr].to_s.scrub.strip.chomp
# Payload
payload = opts[:payload]
pkt = PacketFu::ARPPacket.new(config: PacketFu::Utils.whoami?)
# Ethernet Header
pkt.eth_saddr = eth_src unless eth_src.nil?
pkt.eth_daddr = eth_dst unless eth_dst.nil?
pkt.eth_proto = eth_proto
# ARP Header
pkt.arp_hw = arp_hw
pkt.arp_proto = arp_proto
pkt.arp_hw_len = arp_hw_len
pkt.arp_proto_len = arp_proto_len
pkt.arp_opcode = arp_opcode
pkt.arp_saddr_mac = arp_src_mac
pkt.arp_saddr_ip = arp_ip_saddr
pkt.arp_daddr_mac = arp_dst_mac
pkt.arp_daddr_ip = arp_ip_daddr
# Payload
pkt.payload = payload if payload
pkt
rescue StandardError => e
raise e
end
# Supported Method Parameters::
# pkt = PWN::Plugins::Packet.construct_eth(
# ip_saddr: 'required - source ip of packet',
# ip_daddr: 'required - destination ip to send packet',
# payload: 'optional - packet payload defaults to empty string',
# ip_id: 'optional - defaults to 0xfeed',
# iface: 'optional - interface to send packet (defaults to eth0)',
# )
public_class_method def self.construct_eth(opts = {})
# Ethernet Header
eth_src = opts[:eth_src]
eth_dst = opts[:eth_dst]
if opts[:eth_proto]
eth_proto = opts[:eth_proto]
else
eth_proto = 0x0800 # IPv4
end
# Payload
payload = opts[:payload]
pkt = PacketFu::EthPacket.new(config: PacketFu::Utils.whoami?)
# Ethernet Header
pkt.eth_saddr = eth_src unless eth_src.nil?
pkt.eth_daddr = eth_dst unless eth_dst.nil?
pkt.eth_proto = eth_proto
# Payload
pkt.payload = payload if payload
pkt
rescue StandardError => e
raise e
end
# Supported Method Parameters::
# pkt = PWN::Plugins::Packet.construct_hsrp(
# ip_saddr: 'required - source ip of packet',
# ip_daddr: 'required - destination ip to send packet',
# payload: 'optional - packet payload defaults to empty string',
# ip_id: 'optional - defaults to 0xfeed',
# iface: 'optional - interface to send packet (defaults to eth0)',
# )
public_class_method def self.construct_hsrp(opts = {})
# Ethernet Header
eth_src = opts[:eth_src]
eth_dst = opts[:eth_dst]
if opts[:eth_proto]
eth_proto = opts[:eth_proto]
else
eth_proto = 0x0800 # IPv4
end
# IP Header
if opts[:ip_v]
ip_v = opts[:ip_v]
else
ip_v = 4
end
if opts[:ip_hl]
ip_hl = opts[:ip_hl]
else
ip_hl = 5
end
if opts[:ip_tos]
ip_tos = opts[:ip_tos]
else
ip_tos = 0
end
if opts[:ip_len]
ip_len = opts[:ip_len]
else
ip_len = 20
end
if opts[:ip_id]
ip_id = opts[:ip_id]
else
ip_id = 0xfeed
end
if opts[:ip_frag]
ip_frag = opts[:ip_frag]
else
ip_frag = 0
end
if opts[:ip_ttl]
ip_ttl = opts[:ip_ttl]
else
ip_ttl = 32
end
if opts[:ip_proto]
ip_proto = opts[:ip_proto]
else
ip_proto = 17 # UDP
end
if opts[:ip_sum]
ip_sum = opts[:ip_sum]
else
ip_sum = 0xffff
end
ip_saddr = opts[:ip_saddr]
ip_daddr = opts[:ip_daddr]
# UDP Header
udp_src_port = opts[:udp_src_port]
udp_dst_port = opts[:udp_dst_port]
if opts[:udp_len]
udp_len = opts[:udp_len]
else
udp_len = 8
end
if opts[:udp_sum]
udp_sum = opts[:udp_sum]
else
udp_sum = 0x0000
end
# HSRP Header
if opts[:hsrp_version]
hsrp_version = opts[:hsrp_version]
else
hsrp_version = 0
end
if opts[:hsrp_opcode]
hsrp_opcode = opts[:hsrp_opcode]
else
hsrp_opcode = 0
end
if opts[:hsrp_state]
hsrp_state = opts[:hsrp_state]
else
hsrp_state = 0
end
if opts[:hsrp_hellotime]
hsrp_state = opts[:hsrp_hellotime]
else
hsrp_state = 3
end
if opts[:hsrp_holdtime]
hsrp_holdtime = opts[:hsrp_holdtime]
else
hsrp_holdtime = 10
end
if opts[:hsrp_priority]
hsrp_priority = opts[:hsrp_priority]
else
hsrp_priority = 0
end
if opts[:hsrp_group]
hsrp_group = opts[:hsrp_group]
else
hsrp_group = 0
end
if opts[:hsrp_reserved]
hsrp_reserved = opts[:hsrp_reserved]
else
hsrp_reserved = 0
end
if opts[:hsrp_password]
hsrp_password = opts[:hsrp_password]
else
hsrp_password = "cicso\x00\x00\x00"
end
if opts[:hsrp_addr]
hsrp_addr = opts[:hsrp_addr]
else
hsrp_addr = '0.0.0.0'
end
# Payload
payload = opts[:payload]
pkt = PacketFu::HSRPPacket.new(config: PacketFu::Utils.whoami?)
# Ethernet Header
pkt.eth_saddr = eth_src unless eth_src.nil?
pkt.eth_daddr = eth_dst unless eth_dst.nil?
pkt.eth_proto = eth_proto
# IP Header
pkt.ip_v = ip_v
pkt.ip_hl = ip_hl
pkt.ip_tos = ip_tos
pkt.ip_len = ip_len
pkt.ip_id = ip_id
pkt.ip_frag = ip_frag
pkt.ip_ttl = ip_ttl
pkt.ip_proto = ip_proto
pkt.ip_sum = ip_sum
pkt.ip_saddr = ip_saddr
pkt.ip_daddr = ip_daddr
# UDP Header
pkt.udp_src = udp_src_port if udp_src_port
pkt.udp_dst = udp_dst_port if udp_dst_port
pkt.udp_len = udp_len
pkt.udp_sum = udp_sum
# HSRP Header
pkt.hsrp_version = hsrp_version
pkt.hsrp_opcode = hsrp_opcode
pkt.hsrp_state = hsrp_state
pkt.hsrp_hellotime = hsrp_hellotime
pkt.hsrp_holdtime = hsrp_holdtime
pkt.hsrp_priority = hsrp_priority
pkt.hsrp_group = hsrp_group
pkt.hsrp_reserved = hsrp_reserved
pkt.hsrp_password = hsrp_password
pkt.hsrp_addr = hsrp_addr
# Payload
pkt.payload = payload if payload
pkt
rescue StandardError => e
raise e
end
# Supported Method Parameters::
# pkt = PWN::Plugins::Packet.construct_icmp(
# ip_saddr: 'required - source ip of packet',
# ip_daddr: 'required - destination ip to send packet',
# payload: 'optional - packet payload defaults to "*ping*"',
# ip_id: 'optional - defaults to 0xfeed',
# iface: 'optional - interface to send packet (defaults to eth0)',
# )
public_class_method def self.construct_icmp(opts = {})
# Ethernet Header
eth_src = opts[:eth_src]
eth_dst = opts[:eth_dst]
if opts[:eth_proto]
eth_proto = opts[:eth_proto]
else
eth_proto = 0x0800 # IPv4
end
# IP Header
if opts[:ip_v]
ip_v = opts[:ip_v]
else
ip_v = 4
end
if opts[:ip_hl]
ip_hl = opts[:ip_hl]
else
ip_hl = 5
end
if opts[:ip_tos]
ip_tos = opts[:ip_tos]
else
ip_tos = 0
end
if opts[:ip_len]
ip_len = opts[:ip_len]
else
ip_len = 20
end
if opts[:ip_id]
ip_id = opts[:ip_id]
else
ip_id = 0xfeed
end
if opts[:ip_frag]
ip_frag = opts[:ip_frag]
else
ip_frag = 0
end
if opts[:ip_ttl]
ip_ttl = opts[:ip_ttl]
else
ip_ttl = 32
end
if opts[:ip_proto]
ip_proto = opts[:ip_proto]
else
ip_proto = 1 # ICMP
end
if opts[:ip_sum]
ip_sum = opts[:ip_sum]
else
ip_sum = 0xffff
end
ip_saddr = opts[:ip_saddr]
ip_daddr = opts[:ip_daddr]
# ICMP Header
if opts[:icmp_type]
icmp_type = opts[:icmp_type]
else
icmp_type = 8
end
if opts[:icmp_code]
icmp_code = opts[:icmp_code]
else
icmp_code = 0
end
if opts[:icmp_sum]
icmp_sum = opts[:icmp_sum]
else
icmp_sum = 0xffff
end
# Payload
opts[:payload] ? payload = opts[:payload] : payload = '*ping*'
pkt = PacketFu::ICMPPacket.new(config: PacketFu::Utils.whoami?)
# Ethernet Header
pkt.eth_saddr = eth_src unless eth_src.nil?
pkt.eth_daddr = eth_dst unless eth_dst.nil?
pkt.eth_proto = eth_proto
# IP Header
pkt.ip_v = ip_v
pkt.ip_hl = ip_hl
pkt.ip_tos = ip_tos
pkt.ip_len = ip_len
pkt.ip_id = ip_id
pkt.ip_frag = ip_frag
pkt.ip_ttl = ip_ttl
pkt.ip_proto = ip_proto
pkt.ip_sum = ip_sum
pkt.ip_saddr = ip_saddr
pkt.ip_daddr = ip_daddr
# ICMP Header
pkt.icmp_type = icmp_type
pkt.icmp_code = icmp_code
pkt.icmp_sum = icmp_sum
# Payload
pkt.payload = payload if payload
pkt
rescue StandardError => e
raise e
end
# Supported Method Parameters::
# pkt = PWN::Plugins::Packet.construct_icmpv6(
# ip_saddr: 'required - source ip of packet',
# ip_daddr: 'required - destination ip to send packet',
# payload: 'optional - packet payload defaults to empty string',
# ip_id: 'optional - defaults to 0xfeed',
# iface: 'optional - interface to send packet (defaults to eth0)',
# )
public_class_method def self.construct_icmpv6(opts = {})
# Ethernet Header
eth_src = opts[:eth_src]
eth_dst = opts[:eth_dst]
if opts[:eth_proto]
eth_proto = opts[:eth_proto]
else
eth_proto = 0x86dd # IPv6
end
# IPv6 Header
if opts[:ipv6_v]
ipv6_v = opts[:ipv6_v]
else
ipv6_v = 6
end
if opts[:ipv6_class]
ipv6_class = opts[:ipv6_class]
else
ipv6_class = 0
end
if opts[:ipv6_label]
ipv6_label = opts[:ipv6_label]
else
ipv6_label = 0
end
if opts[:ipv6_len]
ipv6_len = opts[:ipv6_len]
else
ipv6_len = 0
end
if opts[:ipv6_next]
ipv6_next = opts[:ipv6_next]
else
ipv6_next = 58
end
if opts[:ipv6_hop]
ipv6_hop = opts[:ipv6_hop]
else
ipv6_hop = 255
end
ipv6_saddr = opts[:ipv6_saddr]
ipv6_daddr = opts[:ipv6_daddr]
# ICMPv6 Header
if opts[:icmpv6_type]
icmpv6_type = opts[:icmpv6_type]
else
icmp_type = 8
end
if opts[:icmpv6_code]
icmpv6_code = opts[:icmpv6_code]
else
icmpv6_code = 0
end
if opts[:icmpv6_sum]
icmp_sum = opts[:icmpv6_sum]
else
icmpv6_sum = 0x0000
end
# Payload
payload = opts[:payload]
pkt = PacketFu::IPv6Packet.new(config: PacketFu::Utils.whoami?)
# Ethernet Header
pkt.eth_saddr = eth_src unless eth_src.nil?
pkt.eth_daddr = eth_dst unless eth_dst.nil?
pkt.eth_proto = eth_proto
# IPv6 Header
pkt.ipv6_v = ipv6_v
pkt.ipv6_hl = ipv6_hl
pkt.ipv6_tos = ipv6_tos
pkt.ipv6_len = ipv6_len
pkt.ipv6_id = ipv6_id
pkt.ipv6_frag = ipv6_frag
pkt.ipv6_saddr = ipv6_saddr
pkt.ipv6_daddr = ipv6_daddr
# ICMPv6 Header
pkt.icmpv6_type = icmpv6_type
pkt.icmpv6_code = icmpv6_code
pkt.icmpv6_sum = icmpv6_sum
# Payload
pkt.payload = payload if payload
pkt
rescue StandardError => e
raise e
end
# Supported Method Parameters::
# pkt = PWN::Plugins::Packet.construct_ip(
# ip_saddr: 'required - source ip of packet',
# ip_daddr: 'required - destination ip to send packet',
# payload: 'optional - packet payload defaults to empty string',
# ip_id: 'optional - defaults to 0xfeed',
# iface: 'optional - interface to send packet (defaults to eth0)',
# )
public_class_method def self.construct_ip(opts = {})
# Ethernet Header
eth_src = opts[:eth_src]
eth_dst = opts[:eth_dst]
if opts[:eth_proto]
eth_proto = opts[:eth_proto]
else
eth_proto = 0x0800 # IPv4
end
# IP Header
if opts[:ip_v]
ip_v = opts[:ip_v]
else
ip_v = 4
end
if opts[:ip_hl]
ip_hl = opts[:ip_hl]
else
ip_hl = 5
end
if opts[:ip_tos]
ip_tos = opts[:ip_tos]
else
ip_tos = 0
end
if opts[:ip_len]
ip_len = opts[:ip_len]
else
ip_len = 20
end
if opts[:ip_id]
ip_id = opts[:ip_id]
else
ip_id = 0xfeed
end
if opts[:ip_frag]
ip_frag = opts[:ip_frag]
else
ip_frag = 0
end
if opts[:ip_ttl]
ip_ttl = opts[:ip_ttl]
else
ip_ttl = 32
end
if opts[:ip_proto]
ip_proto = opts[:ip_proto]
else
ip_proto = -1
end
if opts[:ip_sum]
ip_sum = opts[:ip_sum]
else
ip_sum = 0xffff
end
ip_saddr = opts[:ip_saddr]
ip_daddr = opts[:ip_daddr]
# Payload
payload = opts[:payload]
pkt = PacketFu::IPPacket.new(config: PacketFu::Utils.whoami?)
# Ethernet Header
pkt.eth_saddr = eth_src unless eth_src.nil?
pkt.eth_daddr = eth_dst unless eth_dst.nil?
pkt.eth_proto = eth_proto
# IP Header
pkt.ip_v = ip_v
pkt.ip_hl = ip_hl
pkt.ip_tos = ip_tos
pkt.ip_len = ip_len
pkt.ip_id = ip_id
pkt.ip_frag = ip_frag
pkt.ip_ttl = ip_ttl
pkt.ip_proto = ip_proto
pkt.ip_sum = ip_sum
pkt.ip_saddr = ip_saddr
pkt.ip_daddr = ip_daddr
# Payload
pkt.payload = payload if payload
pkt
rescue StandardError => e
raise e
end
# Supported Method Parameters::
# pkt = PWN::Plugins::Packet.construct_ipv6(
# ip_saddr: 'required - source ip of packet',
# ip_daddr: 'required - destination ip to send packet',
# payload: 'optional - packet payload defaults to empty string',
# ip_id: 'optional - defaults to 0xfeed',
# iface: 'optional - interface to send packet (defaults to eth0)',
# )
public_class_method def self.construct_ipv6(opts = {})
# Ethernet Header
eth_src = opts[:eth_src]
eth_dst = opts[:eth_dst]
if opts[:eth_proto]
eth_proto = opts[:eth_proto]
else
eth_proto = 0x86dd # IPv6
end
# IPv6 Header
if opts[:ipv6_v]
ipv6_v = opts[:ipv6_v]
else
ipv6_v = 6
end
if opts[:ipv6_class]
ipv6_class = opts[:ipv6_class]
else
ipv6_class = 0
end
if opts[:ipv6_label]
ipv6_label = opts[:ipv6_label]
else
ipv6_label = 0
end
if opts[:ipv6_len]
ipv6_len = opts[:ipv6_len]
else
ipv6_len = 0
end
if opts[:ipv6_next]
ipv6_next = opts[:ipv6_next]
else
ipv6_next = 0
end
if opts[:ipv6_hop]
ipv6_hop = opts[:ipv6_hop]
else
ipv6_hop = 255
end
ipv6_saddr = opts[:ipv6_saddr]
ipv6_daddr = opts[:ipv6_daddr]
# Payload
payload = opts[:payload]
pkt = PacketFu::IPv6Packet.new(config: PacketFu::Utils.whoami?)
# Ethernet Header
pkt.eth_saddr = eth_src unless eth_src.nil?
pkt.eth_daddr = eth_dst unless eth_dst.nil?
pkt.eth_proto = eth_proto
# IPv6 Header
pkt.ipv6_v = ipv6_v
pkt.ipv6_hl = ipv6_hl
pkt.ipv6_tos = ipv6_tos
pkt.ipv6_len = ipv6_len
pkt.ipv6_id = ipv6_id
pkt.ipv6_frag = ipv6_frag
pkt.ipv6_saddr = ipv6_saddr
pkt.ipv6_daddr = ipv6_daddr
# Payload
pkt.payload = payload if payload
pkt
rescue StandardError => e
raise e
end
# Supported Method Parameters::
# pkt = PWN::Plugins::Packet.construct_tcp(
# ip_saddr: 'required - source ip of packet',
# ip_daddr: 'required - destination ip to send packet',
# payload: 'optional - packet payload defaults to empty string',
# ip_id: 'optional - defaults to 0xfeed',
# iface: 'optional - interface to send packet (defaults to eth0)',
# )
public_class_method def self.construct_tcp(opts = {})
# Ethernet Header
eth_src = opts[:eth_src]
eth_dst = opts[:eth_dst]
if opts[:eth_proto]
eth_proto = opts[:eth_proto]
else
eth_proto = 0x0800 # IPv4
end
# IP Header
if opts[:ip_v]
ip_v = opts[:ip_v]
else
ip_v = 4
end
if opts[:ip_hl]
ip_hl = opts[:ip_hl]
else
ip_hl = 5
end
if opts[:ip_tos]
ip_tos = opts[:ip_tos]
else
ip_tos = 0
end
if opts[:ip_len]
ip_len = opts[:ip_len]
else
ip_len = 20
end
if opts[:ip_id]
ip_id = opts[:ip_id]
else
ip_id = 0xfeed
end
if opts[:ip_frag]
ip_frag = opts[:ip_frag]
else
ip_frag = 0
end
if opts[:ip_ttl]
ip_ttl = opts[:ip_ttl]
else
ip_ttl = 32
end
if opts[:ip_proto]
ip_proto = opts[:ip_proto]
else
ip_proto = 6 # TCP
end
if opts[:ip_sum]
ip_sum = opts[:ip_sum]
else
ip_sum = 0xffff
end
ip_saddr = opts[:ip_saddr]
ip_daddr = opts[:ip_daddr]
# TCP Header
tcp_src_port = opts[:tcp_src_port]
tcp_dst_port = opts[:tcp_dst_port]
if opts[:tcp_seq]
tcp_seq = opts[:tcp_seq]
else
tcp_seq = 0x5fcea416
end
if opts[:tcp_ack]
tcp_ack = opts[:tcp_ack]
else
tcp_ack = 0x00000000
end
if opts[:tcp_hlen]
tcp_hlen = opts[:tcp_hlen]
else
tcp_hlen = 5
end
if opts[:tcp_reserved]
tcp_reserved = opts[:tcp_reserved]
else
tcp_reserved = 0
end
if opts[:tcp_ecn]
tcp_ecn = opts[:tcp_ecn]
else
tcp_ecn = 0
end
tcp_flags = opts[:tcp_flags]
if opts[:tcp_win]
tcp_win = opts[:tcp_win]
else
tcp_win = 16_384
end
if opts[:tcp_sum]
tcp_sum = opts[:tcp_sum]
else
tcp_sum = 0x1ab2
end
if opts[:tcp_urg]
tcp_urg = opts[:tcp_urg]
else
tcp_urg = 0
end
tcp_opts = opts[:tcp_opts]
# Payload
payload = opts[:payload]
pkt = PacketFu::TCPPacket.new(config: PacketFu::Utils.whoami?)
# Ethernet Header
pkt.eth_saddr = eth_src unless eth_src.nil?
pkt.eth_daddr = eth_dst unless eth_dst.nil?
pkt.eth_proto = eth_proto
# IP Header
pkt.ip_v = ip_v
pkt.ip_hl = ip_hl
pkt.ip_tos = ip_tos
pkt.ip_len = ip_len
pkt.ip_id = ip_id
pkt.ip_frag = ip_frag
pkt.ip_ttl = ip_ttl
pkt.ip_proto = ip_proto
pkt.ip_sum = ip_sum
pkt.ip_saddr = ip_saddr
pkt.ip_daddr = ip_daddr
# TCP Header
pkt.tcp_src = tcp_src_port if tcp_src_port
pkt.tcp_dst = tcp_dst_port if tcp_dst_port
pkt.tcp_seq = tcp_seq
pkt.tcp_ack = tcp_ack
pkt.tcp_hlen = tcp_hlen
pkt.tcp_reserved = tcp_reserved
pkt.tcp_ecn = tcp_ecn
pkt.tcp_flags = PacketFu::TcpFlags.new
pkt.tcp_win = tcp_win
pkt.tcp_sum = tcp_sum
pkt.tcp_urg = tcp_urg
pkt.tcp_opts = PacketFu::TcpOptions.new
# Payload
pkt.payload = payload if payload
pkt
rescue StandardError => e
raise e
end
# Supported Method Parameters::
# pkt = PWN::Plugins::Packet.construct_udp(
# ip_saddr: 'required - source ip of packet',
# ip_daddr: 'required - destination ip to send packet',
# payload: 'optional - packet payload defaults to empty string',
# ip_id: 'optional - defaults to 0xfeed',
# iface: 'optional - interface to send packet (defaults to eth0)',
# )
public_class_method def self.construct_udp(opts = {})
# Ethernet Header
eth_src = opts[:eth_src]
eth_dst = opts[:eth_dst]
if opts[:eth_proto]
eth_proto = opts[:eth_proto]
else
eth_proto = 0x0800 # IPv4
end
# IP Header
if opts[:ip_v]
ip_v = opts[:ip_v]
else
ip_v = 4
end
if opts[:ip_hl]
ip_hl = opts[:ip_hl]
else
ip_hl = 5
end
if opts[:ip_tos]
ip_tos = opts[:ip_tos]
else
ip_tos = 0
end
if opts[:ip_len]
ip_len = opts[:ip_len]
else
ip_len = 20
end
if opts[:ip_id]
ip_id = opts[:ip_id]
else
ip_id = 0xfeed
end
if opts[:ip_frag]
ip_frag = opts[:ip_frag]
else
ip_frag = 0
end
if opts[:ip_ttl]
ip_ttl = opts[:ip_ttl]
else
ip_ttl = 32
end
if opts[:ip_proto]
ip_proto = opts[:ip_proto]
else
ip_proto = 17 # UDP
end
if opts[:ip_sum]
ip_sum = opts[:ip_sum]
else
ip_sum = 0xffff
end
ip_saddr = opts[:ip_saddr]
ip_daddr = opts[:ip_daddr]
# UDP Header
udp_src_port = opts[:udp_src_port]
udp_dst_port = opts[:udp_dst_port]
if opts[:udp_len]
udp_len = opts[:udp_len]
else
udp_len = 8
end
if opts[:udp_sum]
udp_sum = opts[:udp_sum]
else
udp_sum = 0xffde
end
# Payload
payload = opts[:payload]
pkt = PacketFu::UDPPacket.new(config: PacketFu::Utils.whoami?)
# Ethernet Header
pkt.eth_saddr = eth_src unless eth_src.nil?
pkt.eth_daddr = eth_dst unless eth_dst.nil?
pkt.eth_proto = eth_proto
# IP Header
pkt.ip_v = ip_v
pkt.ip_hl = ip_hl
pkt.ip_tos = ip_tos
pkt.ip_len = ip_len
pkt.ip_id = ip_id
pkt.ip_frag = ip_frag
pkt.ip_ttl = ip_ttl
pkt.ip_proto = ip_proto
pkt.ip_sum = ip_sum
pkt.ip_saddr = ip_saddr
pkt.ip_daddr = ip_daddr
# UDP Header
pkt.udp_src = udp_src_port if udp_src_port
pkt.udp_dst = udp_dst_port if udp_dst_port
pkt.udp_len = udp_len
pkt.udp_sum = udp_sum
# Payload
pkt.payload = payload if payload
pkt
rescue StandardError => e
raise e
end
# Supported Method Parameters::
# PWN::Plugins::Packet.send(
# pkt: 'required - pkt returned from other #construct_<type> methods',
# iface: 'optional - interface to send packet (defaults to eth0)',
# )
public_class_method def self.send(opts = {})
pkt = opts[:pkt]
if opts[:iface]
iface = opts[:iface].to_s.scrub.strip.chomp
else
iface = 'eth0'
end
if pkt.instance_of?(PacketFu::TCPPacket)
this_ip = Socket.ip_address_list.detect(&:ipv4_private?).ip_address
# If we're not passing a RST packet, prevent kernel from sending its own
if this_ip == pkt.ip_saddr && pkt.tcp_flags.rst.zero?
# We have to prevent the kernel space from sending a RST
# because it won't have a socket open on the respective
# port number before we have a chance to do anything.
# In other words, the kernel will receive a SYN-ACK first,
# know it didn't send a SYN & send a RST as a result.
my_os = PWN::Plugins::DetectOS.type
case my_os
when :linux
ipfilter = 'sudo iptables'
chain_action = '-C'
ipfilter_rule = "OUTPUT --protocol tcp --source #{pkt.ip_saddr} --destination #{pkt.ip_daddr} --destination-port #{pkt.tcp_dst} --tcp-flags RST RST -j DROP"
ipfilter_cmd = "#{ipfilter} #{chain_action} #{ipfilter_rule}"
unless system(ipfilter_cmd, out: File::NULL, err: File::NULL)
chain_action = '-A'
ipfilter_cmd = "#{ipfilter} #{chain_action} #{ipfilter_rule}"
puts 'Preventing kernel from misbehaving when manipulating packets.'
puts 'Creating the following iptables rule:'
puts ipfilter_cmd
system(ipfilter_cmd)
puts "Be sure to delete iptables rule, once completed. Here's how:"
chain_action = '-D'
ipfilter_cmd = "#{ipfilter} #{chain_action} #{ipfilter_rule}"
puts ipfilter_cmd
end
pkt.recalc
pkt.to_w(iface)
system(ipfilter, "-D #{ipfilter_rule}")
# when :osx
# ipfilter = 'pfctl'
# ipfilter_rule = "block out proto tcp from #{pkt.ip_saddr} to #{pkt.ip_daddr} port #{pkt.tcp_dst} flags R"
# system(ipfilter, "pfctl_add_flag #{ipfilter_rule}")
# pkt.recalc
# pkt.to_w(iface)
# system(ipfilter, "pfctl_del_flag #{ipfilter_rule}")
else
raise "ERROR: #{self} Does not Support #{my_os}"
end
end
else
pkt.recalc
pkt.to_w(iface)
end
rescue StandardError => e
raise e
end
# Author(s):: 0day Inc. <request.pentest@0dayinc.com>
public_class_method def self.authors
"AUTHOR(S):
0day Inc. <request.pentest@0dayinc.com>
"
end
# Display Usage for this Module
public_class_method def self.help
puts "USAGE:
pcap = #{self}.open_pcap_file(
path: 'required - path to packet capture file'
)
pcap[0].public_methods
pcap.each do |p|
print \"IP ID: \#{p.ip_id_readable} \"
print \"IP Sum: \#{p.ip_sum_readable} \"
print \"SRC IP: \#{p.ip_src_readable} \"
print \"SRC MAC: (\#{p.eth_src_readable}) \"
print \"TCP SRC PORT: \#{p.tcp_sport} => \"
print \"DST IP: \#{p.ip_dst_readable} \"
print \"DST MAC: (\#{p.eth_dst_readable}) \"
print \"TCP DST PORT: \#{p.tcp_dport} \"
print \"ETH PROTO: \#{p.eth_proto_readable} \"
print \"TCP FLAGS: \#{p.tcp_flags_readable} \"
print \"TCP ACK: \#{p.tcp_ack_readable} \"
print \"TCP SEQ: \#{p.tcp_seq_readable} \"
print \"TCP SUM: \#{p.tcp_sum_readable} \"
print \"TCP OPTS: \#{p.tcp_opts_readable} \"
puts \"BODY: \#{p.hexify(p.payload)}\"
puts \"\\n\\n\\n\"
end
pkt = #{self}.construct_arp(
ip_saddr: 'required - source ip of packet',
ip_daddr: 'required - destination ip to send packet',
payload: 'optional - packet payload defaults to empty string',
ip_id: 'optional - defaults to 0xfeed',
iface: 'optional - interface to send packet (defaults to eth0)',
)
pkt = #{self}.construct_eth(
ip_saddr: 'required - source ip of packet',
ip_daddr: 'required - destination ip to send packet',
payload: 'optional - packet payload defaults to empty string',
ip_id: 'optional - defaults to 0xfeed',
iface: 'optional - interface to send packet (defaults to eth0)',
)
pkt = #{self}.construct_hsrp(
ip_saddr: 'required - source ip of packet',
ip_daddr: 'required - destination ip to send packet',
payload: 'optional - packet payload defaults to empty string',
ip_id: 'optional - defaults to 0xfeed',
iface: 'optional - interface to send packet (defaults to eth0)',
)
pkt = #{self}.construct_icmp(
ip_saddr: 'required - source ip of packet',
ip_daddr: 'required - destination ip to send packet',
payload: 'optional - packet payload defaults to \"*ping*\"',
ip_id: 'optional - defaults to 0xfeed',
iface: 'optional - interface to send packet (defaults to eth0)',
)
pkt = #{self}.construct_icmpv6(
ip_saddr: 'required - source ip of packet',
ip_daddr: 'required - destination ip to send packet',
payload: 'optional - packet payload defaults to empty string',
ip_id: 'optional - defaults to 0xfeed',
iface: 'optional - interface to send packet (defaults to eth0)',
)
pkt = #{self}.construct_ip(
ip_saddr: 'required - source ip of packet',
ip_daddr: 'required - destination ip to send packet',
payload: 'optional - packet payload defaults to empty string',
ip_id: 'optional - defaults to 0xfeed',
iface: 'optional - interface to send packet (defaults to eth0)',
)
pkt = #{self}.construct_ipv6(
ip_saddr: 'required - source ip of packet',
ip_daddr: 'required - destination ip to send packet',
payload: 'optional - packet payload defaults to empty string',
ip_id: 'optional - defaults to 0xfeed',
iface: 'optional - interface to send packet (defaults to eth0)',
)
pkt = #{self}.construct_tcp(
ip_saddr: 'required - source ip of packet',
ip_daddr: 'required - destination ip to send packet',
payload: 'optional - packet payload defaults to empty string',
ip_id: 'optional - defaults to 0xfeed',
iface: 'optional - interface to send packet (defaults to eth0)',
)
pkt = #{self}.construct_udp(
ip_saddr: 'required - source ip of packet',
ip_daddr: 'required - destination ip to send packet',
payload: 'optional - packet payload defaults to empty string',
ip_id: 'optional - defaults to 0xfeed',
iface: 'optional - interface to send packet (defaults to eth0)',
)
#{self}.send(
pkt: 'required - pkt returned from other #construct_<type> methods',
iface: 'optional - interface to send packet (defaults to eth0)',
)
#{self}.authors
"
end
end
end
end
| 27.19261 | 170 | 0.539969 |
9142a0875c21eccb6932c0875da90860b3b893c3 | 402 | class FeatureFlagsController < ApiJsonController
skip_authorization_check only: :index
# GET /feature_flags
def index
render json: FeatureFlagService.all
end
# PUT /feature_flags/:flag
def update_flag
authorize! :update, :feature_flags
state = params.require(:feature_flag).require(:state)
FeatureFlagService.create_or_update params[:flag], state
index
end
end
| 18.272727 | 60 | 0.743781 |
1ce3f44f4d2b0079fcd6d515343d9f407436730e | 4,968 | require 'matrix'
require_relative 'size_one'
require_relative 'size_zero'
module Geometry
=begin
An object representing the size of something.
Supports all of the familiar {Vector} methods as well as a few convenience
methods (width, height and depth).
== Usage
=== Constructor
size = Geometry::Size[x,y,z]
=end
class Size < Vector
# Allow vector-style initialization, but override to support copy-init
# from Vector, Point or another Size
#
# @overload [](x,y,z,...)
# @overload [](Point)
# @overload [](Size)
# @overload [](Vector)
# @return [Size] A new {Size} object
def self.[](*array)
array.map! { |a| a.respond_to?(:to_a) ? a.to_a : a }
array.flatten!
super(*array)
end
# Creates and returns a new {SizeOne} instance. Or, a {Size} full of ones if the size argument is given.
# @param size [Number] the size of the new {Size} full of ones
# @return [SizeOne] A new {SizeOne} instance
def self.one(size = nil)
size ? Size[Array.new(size, 1)] : SizeOne.new
end
# Creates and returns a new {SizeOne} instance. Or, a {Size} full of zeros if the size argument is given.
# @param size [Number] the size of the new {Size} full of zeros
# @return [SizeOne] A new {SizeOne} instance
def self.zero(size = nil)
size ? Size[Array.new(size, 0)] : SizeOne.new
end
# Allow comparison with an Array, otherwise do the normal thing
def ==(other)
return @elements == other if other.is_a?(Array)
super other
end
# Override Vector#[] to allow for regular array slicing
def [](*args)
@elements[*args]
end
def coerce(other)
case other
when Array then
[Size[*other], self]
when Numeric then
[Size[Array.new(self.size, other)], self]
when Vector then
[Size[*other], self]
else
raise TypeError, "#{self.class} can't be coerced into #{other.class}"
end
end
def inspect
'Size' + @elements.inspect
end
def to_s
'Size' + @elements.to_s
end
# @return [Number] The size along the Z axis
def depth
z
end
# @return [Number] The size along the Y axis
def height
y
end
# @return [Number] The size along the X axis
def width
x
end
# @return [Number] X-component (width)
def x
@elements[0]
end
# @return [Number] Y-component (height)
def y
@elements[1]
end
# @return [Number] Z-component (depth)
def z
@elements[2]
end
# Create a new {Size} that is smaller than the receiver by the specified amounts
# @overload inset(x,y)
# @param x [Number] the horizontal inset
# @param y [Number] the vertical inset
# @overload inset(options)
# @option options [Number] :left the left inset
# @option options [Number] :right the right inset
# @option options [Number] :top the top inset
# @option options [Number] :bottom the bottom inset
def inset(*args)
options, args = args.partition { |a| a.is_a? Hash }
options = options.reduce({}, :merge)
left = right = top = bottom = 0
if 1 == args.size
left = top = -args.shift
right = bottom = 0
elsif 2 == args.size
left = right = -args.shift
top = bottom = -args.shift
end
left = right = -options[:x] if options[:x]
top = bottom = -options[:y] if options[:y]
top = -options[:top] if options[:top]
left = -options[:left] if options[:left]
bottom = -options[:bottom] if options[:bottom]
right = -options[:right] if options[:right]
self.class[left + width + right, top + height + bottom]
end
# Create a new {Size} that is larger than the receiver by the specified amounts
# @overload outset(x,y)
# @param x [Number] the horizontal inset
# @param y [Number] the vertical inset
# @overload outset(options)
# @option options [Number] :left the left inset
# @option options [Number] :right the right inset
# @option options [Number] :top the top inset
# @option options [Number] :bottom the bottom inset
def outset(*args)
options, args = args.partition { |a| a.is_a? Hash }
options = options.reduce({}, :merge)
left = right = top = bottom = 0
if 1 == args.size
left = top = args.shift
right = bottom = 0
elsif 2 == args.size
left = right = args.shift
top = bottom = args.shift
end
left = right = options[:x] if options[:x]
top = bottom = options[:y] if options[:y]
top = options[:top] if options[:top]
left = options[:left] if options[:left]
bottom = options[:bottom] if options[:bottom]
right = options[:right] if options[:right]
self.class[left + width + right, top + height + bottom]
end
end
end
| 28.067797 | 109 | 0.597222 |
38db19630f8f22c6a047f3ec401adf76ff5cd209 | 152 | json.array!(@categoria) do |categorium|
json.extract! categorium, :id, :codigo, :descripcion
json.url categorium_url(categorium, format: :json)
end
| 30.4 | 54 | 0.75 |
62788821f6e75069b302a8af2eae23bf2930294c | 18,521 | # Something about this spec can cause havoc on specs following.
# somehow in the following specs AR objects are getting created in two different classes
# so when you compare for example User.first.todos.first == Todos.first they are NOT equal huh!
# I suspect that its to with the fact that we remove and reload the classes
# but I got as far as proving that you have to actually create a todoitem and an associated comment
# once you do that the tests after will fail on stmts like this expect(user.todo_items.to_a).to match_array([TodoItem.first])
# because the class of user.todo_items.class != TodoItems.first even though they look exactly the same!!!
require 'spec_helper'
require 'test_components'
describe "relationship permissions" do#, dont_override_default_scope_permissions: true do
before(:all) do
require 'pusher'
require 'pusher-fake'
Pusher.app_id = "MY_TEST_ID"
Pusher.key = "MY_TEST_KEY"
Pusher.secret = "MY_TEST_SECRET"
require "pusher-fake/support/base"
Hyperstack.configuration do |config|
config.transport = :pusher
config.channel_prefix = "synchromesh"
config.opts = {app_id: Pusher.app_id, key: Pusher.key, secret: Pusher.secret}.merge(PusherFake.configuration.web_options)
end
end
before(:each) do
# spec_helper resets the policy system after each test so we have to setup
# before each test
stub_const 'TestApplicationPolicy', Class.new
TestApplicationPolicy.class_eval do
regulate_class_connection { self }
end
ApplicationController.acting_user = nil
size_window(:small, :portrait)
@dummy_cache_item = double("Dummy Cache Item", vector: nil, acting_user: nil)
end
before(:each) do
ActiveRecord::Base.regulate_scope unscoped: nil
ActiveRecord::Base.regulate_default_scope nil
end
after(:each) do
['ApplicationRecord', 'TodoItem', 'Comment'].each do |klass|
Object.send(:remove_const, klass.to_sym) && load("#{klass.underscore}.rb") rescue nil
end
ApplicationController.acting_user = nil
end
context 'on the server side' do
it 'ActiveRecord::Base with by default leave unscoped and all scopes in a dont care state' do
expect { TodoItem.__secure_remote_access_to_all(TodoItem, nil).__secure_collection_check(@dummy_cache_item) }
.to raise_error(Hyperstack::AccessViolation)
end
it 'will allow access to scopes' do
TodoItem.class_eval do
regulate_scope :all
end
expect { TodoItem.__secure_remote_access_to_all(TodoItem, nil).__secure_collection_check(@dummy_cache_item) }
.not_to raise_error
end
it 'will allow access to chained scopes' do
TodoItem.class_eval do
regulate_scope :all
end
r1 = TodoItem.__secure_remote_access_to_all(TodoItem,nil)
expect { r1.__secure_remote_access_to_important(r1, nil).__secure_collection_check(@dummy_cache_item) }
.not_to raise_error
end
it 'will deny access to scopes' do
TodoItem.class_eval do
regulate_scope(:all) { denied! }
end
expect { TodoItem.__secure_remote_access_to_all(TodoItem, nil) }
.to raise_error(Hyperstack::AccessViolation)
end
it "will leave any scope in a don't care state" do
TodoItem.class_eval do
scope :test, -> () { all }
end
test_scope = TodoItem.__secure_remote_access_to_test(TodoItem, nil)
expect { test_scope.__secure_collection_check(@dummy_cache_item) }
.to raise_error(Hyperstack::AccessViolation)
end
it 'will allow access to has_many relationships' do
TodoItem.class_eval do
regulate_relationship :comments
end
new_todo = TodoItem.new
expect { new_todo.__secure_remote_access_to_comments(new_todo, nil).__secure_collection_check(@dummy_cache_item) }
.not_to raise_error
end
it 'will deny access to has_many relationships' do
TodoItem.class_eval do
regulate_relationship(:comments) { denied! }
end
new_todo = TodoItem.new
expect { new_todo.__secure_remote_access_to_comments(new_todo, nil) }
.to raise_error(Hyperstack::AccessViolation)
end
it "will leave the has_many relationship in a don't care state" do
new_todo = TodoItem.new
comments = new_todo.__secure_remote_access_to_comments(new_todo, nil)
expect { comments.__secure_collection_check(@dummy_cache_item) }
.to raise_error(Hyperstack::AccessViolation)
end
it "will not implicitly override a super classes scope access permission" do
ApplicationRecord.class_eval do
regulate_scope :test
end
TodoItem.class_eval do
scope :test, -> () { all }
end
expect { TodoItem.__secure_remote_access_to_test(TodoItem, nil).__secure_collection_check(@dummy_cache_item) }
.not_to raise_error
end
it "will pass any parameters along to the permission proc" do
TodoItem.class_eval do
regulate_scope(:find_string) { |s| denied! if s == 'doa'}
end
expect { TodoItem.__secure_remote_access_to_find_string(TodoItem, nil, 'doa') }
.to raise_error(Hyperstack::AccessViolation)
end
it "finder methods have access to the acting_user methods" do
TodoItem.class_eval do
regulate_scope(:all) { acting_user }
end
expect { TodoItem.__secure_remote_access_to_all(TodoItem, nil).__secure_collection_check(@dummy_cache_item) }
.to raise_error(Hyperstack::AccessViolation)
expect { TodoItem.__secure_remote_access_to_all(TodoItem, true).__secure_collection_check(@dummy_cache_item) }
.not_to raise_error
end
it "finder methods have access to the denied! methods" do
TodoItem.class_eval do
finder_method(:pow) { denied! }
end
expect { TodoItem.__secure_remote_access_to__pow(TodoItem, nil) }
.to raise_error(Hyperstack::AccessViolation)
end
it "server methods have access to the acting_user" do
TodoItem.class_eval do
server_method(:pow) { acting_user }
end
expect(TodoItem.new.__secure_remote_access_to_pow(TodoItem, 'Omar'))
.to eq('Omar')
end
it "server methods have access to the denied! method" do
TodoItem.class_eval do
server_method(:pow) { denied! }
end
expect { TodoItem.new.__secure_remote_access_to_pow(TodoItem, 'Omar') }
.to raise_error(Hyperstack::AccessViolation)
end
it "can set the policy directly on the scope with a proc" do
TodoItem.class_eval do
scope :test, -> () { all }, regulate: -> () { acting_user }
end
expect { TodoItem.__secure_remote_access_to_test(TodoItem, true).__secure_collection_check(@dummy_cache_item) }
.not_to raise_error
expect { TodoItem.__secure_remote_access_to_test(TodoItem, nil).__secure_collection_check(@dummy_cache_item) }
.to raise_error(Hyperstack::AccessViolation)
end
it 'can set the policy directly on the default scope method' do
TodoItem.class_eval do
default_scope -> () { all }, regulate: -> () { denied! if acting_user }
end
expect { TodoItem.__secure_remote_access_to_all(TodoItem, true) }
.to raise_error(Hyperstack::AccessViolation)
expect { TodoItem.__secure_remote_access_to_all(TodoItem, nil) }
.not_to raise_error
end
it 'can set the policy for the default scope (all) using regulate_default_scope' do
TodoItem.class_eval do
regulate_default_scope { denied! if acting_user }
end
expect { TodoItem.__secure_remote_access_to_all(TodoItem, true) }
.to raise_error(Hyperstack::AccessViolation)
expect { TodoItem.__secure_remote_access_to_all(TodoItem, nil) }
.not_to raise_error
end
it "can use 'regulate: truthy-value' to allow access directly on the scope" do
TodoItem.class_eval do
scope :test, -> () { all }, regulate: :always_allow
end
expect { TodoItem.__secure_remote_access_to_test(TodoItem, nil).__secure_collection_check(@dummy_cache_item) }
.not_to raise_error
end
it "can treat 'regulate: falsy-value' as don't care if directly on the scope" do
TodoItem.class_eval do
scope :test, -> () { all }, regulate: nil
end
test_scope = TodoItem.__secure_remote_access_to_test(TodoItem, nil)
expect { test_scope.__secure_collection_check(@dummy_cache_item) }
.to raise_error(Hyperstack::AccessViolation)
end
%i[denied! denied deny].each do |value|
it "can use 'regulate: #{value}' to allow access directly on the scope" do
TodoItem.class_eval do
scope :test, -> () { all }, regulate: value
end
expect { TodoItem.__secure_remote_access_to_test(TodoItem, nil) }
.to raise_error(Hyperstack::AccessViolation)
end
end
it "can set the policy directly on the scope with a proc" do
stub_const 'TodoItem', Class.new(ApplicationRecord)
TodoItem.has_many :comments, regulate: -> () { acting_user }
new_todo = TodoItem.new
expect { new_todo.__secure_remote_access_to_comments(new_todo, true).__secure_collection_check(@dummy_cache_item) }
.not_to raise_error
new_todo = TodoItem.new
expect { new_todo.__secure_remote_access_to_comments(new_todo, nil).__secure_collection_check(@dummy_cache_item) }
.to raise_error(Hyperstack::AccessViolation)
end
it "can use 'regulate: truthy-value' to allow access directly on the scope" do
stub_const 'TodoItem', Class.new(ApplicationRecord)
TodoItem.has_many :comments, regulate: :always_allow
new_todo = TodoItem.new
expect { new_todo.__secure_remote_access_to_comments(new_todo, nil).__secure_collection_check(@dummy_cache_item) }
.not_to raise_error
end
it "can treat 'regulate: falsy-value' as don't care if directly on the scope" do
stub_const 'TodoItem', Class.new(ApplicationRecord)
TodoItem.has_many :comments, regulate: nil
new_todo = TodoItem.new
comments = new_todo.__secure_remote_access_to_comments(new_todo, nil)
expect { comments.__secure_collection_check(@dummy_cache_item) }
.to raise_error(Hyperstack::AccessViolation)
end
%i[denied! denied deny].each do |value|
it "can use 'regulate: #{value}' to allow access directly on the scope" do
stub_const 'TodoItem', Class.new(ApplicationRecord)
TodoItem.has_many :comments, regulate: value
new_todo = TodoItem.new
expect { new_todo.__secure_remote_access_to_comments(new_todo, nil) }
.to raise_error(Hyperstack::AccessViolation)
end
end
end
context 'integration test', js: true do
before(:each) do
client_option raise_on_js_errors: :off
ApplicationController.acting_user = User.new(first_name: 'fred')
end
context 'with synchromesh running' do
before(:each) do
TestApplicationPolicy.class_eval do
regulate_all_broadcasts { |policy| policy.send_all }
end
end
it 'will allow access via scopes' do
isomorphic do
TodoItem.scope :annuder_scope, ->() { all }
TodoItem.scope :test_scope, ->() { all }, regulate: :always_allow
end
TodoItem.create
mount 'TestComponentZ' do
class TestComponentZ < HyperComponent
render do
DIV { "There is #{TodoItem.annuder_scope.test_scope.count} TodoItem" }
end
end
end
expect(page).to have_content("There is 1 TodoItem")
TodoItem.create
expect(page).to have_content("There is 2 TodoItem")
end
it 'will fail if direct access to relationships is attempted' do
# scopes and permissions are chained, and so you cannot fail until the
# entire chain has been evaluated. The permission mechanism needs to
# have a final *all or *count operation to trigger the permission
# evaluation. A hacker could present a vector without final *all or
# *count, and thus get the entire scope result returned. To pervent this
# an explicit check insures vectors never return raw relationships.
# Here we hack the Fetch Operation (like a Hacker might) but we should
# get an error back instead of data.
mount 'TestComponentZ' do
module ReactiveRecord
class Base
class << self
attr_accessor :last_log_message
def log(*args)
Base.last_log_message = args
end
end
end
class Operations::Fetch < Operations::Base
class << self
alias unmodified_serialize_params serialize_params
def serialize_params(hash)
hash['pending_fetches'][0].pop
unmodified_serialize_params hash
end
end
end
end
class TestComponentZ < HyperComponent
render do
DIV { "There is #{TodoItem.count} TodoItem" }
end
end
end
expect_evaluate_ruby('ReactiveRecord::Base.last_log_message').to eq(['Fetch failed', 'error'])
end
it 'will allow access via relationships' do
isomorphic do
TodoItem.regulate_relationship comments: true
end
todo_item = TodoItem.create
Comment.create(todo_item: todo_item)
mount 'TestComponentZ' do
class TestComponentZ < HyperComponent
render do
DIV { "There is #{TodoItem.find(1).comments.count} comments on the first TodoItem" }
end
end
end
expect(page).to have_content("There is 1 comments on the first TodoItem")
Comment.create(todo_item: todo_item)
expect(page).to have_content("There is 2 comments on the first TodoItem")
end
it 'will protect access via scopes' do
isomorphic do
TodoItem.scope :test_scope, -> () { all } # no regulation implies "don't know"
end
2.times { TodoItem.create }
mount 'TestComponentZ' do
class TestComponentZ < HyperComponent
render do
DIV { "There is #{TodoItem.test_scope.count} TodoItem" }
end
end
end
expect(page).to have_content("There is 1 TodoItem") # should be 2 but will never update
TodoItem.create
wait_for_ajax
expect(page).to have_content("There is 1 TodoItem") # it will never change because scope is not allowed
end
it 'will allow access via relationships' do
isomorphic do
TodoItem.regulate_relationship comments: true
end
todo_item = TodoItem.create
2.times { Comment.create(todo_item: todo_item) }
mount 'TestComponentZ' do
class TestComponentZ < HyperComponent
render do
DIV { "There are #{TodoItem.find(1).comments.count} comments on the first TodoItem" }
end
end
end
wait_for_ajax
expect(page).to have_content("There are 2 comments on the first TodoItem")
end
it 'relationships will inherit the all regulation' do
isomorphic do
ActiveRecord::Base.regulate_scope all: true
end
todo_item = TodoItem.create
2.times { Comment.create(todo_item: todo_item) }
mount 'TestComponentZ' do
class TestComponentZ < HyperComponent
render do
DIV { "There are #{TodoItem.find(1).comments.all.count} comments on the first TodoItem" }
end
end
end
expect(page).to have_content("There are 2 comments on the first TodoItem")
end
end
context 'without synchromesh running' do
before(:each) do
isomorphic do
TodoItem.class_eval do
scope :test_scope1, -> () { all }, regulate: -> () { acting_user }
scope :test_scope2, -> () { all }, regulate: -> () { !acting_user }
server_method(:pow) { denied! unless user == acting_user; acting_user.first_name }
TodoItem.regulate_relationship(:comments) { acting_user == user }
end
end
mount 'DummyComponent' do
class DummyComponent < HyperComponent
render(DIV) { 'hello' }
end
module ReactiveRecord
class Base
class << self
attr_accessor :last_log_message
def log(*args)
Base.last_log_message = args
end
end
end
end
end
end
it 'will control access via relationships' do
class TodoItem < ApplicationRecord
def view_permitted?(attribute)
true
end
end
todo_item1 = TodoItem.create(user: ApplicationController.acting_user)
todo_item2 = TodoItem.create(user: nil)
Comment.create(todo_item: todo_item1)
Comment.create(todo_item: todo_item1)
expect_promise("ReactiveRecord.load { TodoItem.find(#{todo_item1.id}).comments.count }").to eq(2)
expect_promise("ReactiveRecord.load { TodoItem.find(#{todo_item2.id}).comments.count }").not_to eq(0)
expect_evaluate_ruby('ReactiveRecord::Base.last_log_message').to eq(['Fetch failed', 'error'])
end
it 'will control access via scope' do
2.times { TodoItem.create }
expect_promise("ReactiveRecord.load { TodoItem.test_scope1.count }").to eq(2)
expect_promise("ReactiveRecord.load { TodoItem.test_scope2.count }").not_to eq(2)
expect_evaluate_ruby('ReactiveRecord::Base.last_log_message').to eq(['Fetch failed', 'error'])
end
it 'will allow server_methods to control access' do
class TodoItem < ApplicationRecord
def view_permitted?(attribute)
true
end
end
todo_item1 = TodoItem.create(user: ApplicationController.acting_user)
todo_item2 = TodoItem.create(user: User.create(first_name: 'fred'))
expect_promise("ReactiveRecord.load { TodoItem.find(#{todo_item1.id}).pow }").to eq('fred')
expect_promise("ReactiveRecord.load { TodoItem.find(#{todo_item2.id}).pow }").not_to eq('fred')
expect_evaluate_ruby('ReactiveRecord::Base.last_log_message').to eq(['Fetch failed', 'error'])
end
end
end
end
| 39.322718 | 127 | 0.665623 |
262f687fd453220ec8e13f29a930dfe76a753cce | 3,494 | # frozen_string_literal: true
module Solargraph
module CoreFills
Override = Pin::Reference::Override
KEYWORDS = [
'__ENCODING__', '__LINE__', '__FILE__', 'BEGIN', 'END', 'alias', 'and',
'begin', 'break', 'case', 'class', 'def', 'defined?', 'do', 'else',
'elsif', 'end', 'ensure', 'false', 'for', 'if', 'in', 'module', 'next',
'nil', 'not', 'or', 'redo', 'rescue', 'retry', 'return', 'self', 'super',
'then', 'true', 'undef', 'unless', 'until', 'when', 'while', 'yield'
].freeze
methods_with_yieldparam_subtypes = %w[
Array#each Array#map Array#any? Array#all? Array#index Array#keep_if
Array#delete_if
Enumerable#each_entry Enumerable#map Enumerable#any? Enumerable#all?
Enumerable#select Enumerable#reject
Set#each
]
OVERRIDES = [
Override.method_return('Array#keep_if', 'self'),
Override.method_return('Array#delete_if', 'self'),
Override.from_comment('Array#reject', %(
@overload reject(&block)
@return [self]
@overload reject()
@return [Enumerator]
)),
Override.method_return('Array#reverse', 'self', delete: ['overload']),
Override.from_comment('Array#select', %(
@overload select(&block)
@return [self]
@overload select()
@return [Enumerator]
)),
Override.from_comment('Array#[]', %(
@overload [](range)
@param range [Range]
@return [self]
@overload [](num1, num2)
@param num1 [Integer]
@param num2 [Integer]
@return [self]
@overload [](num)
@param num [Integer]
@return_single_parameter
@return_single_parameter
)),
Override.from_comment('Array#first', %(
@overload first(num)
@param num [Integer]
@return [self]
@return_single_parameter
)),
Override.from_comment('Array#last', %(
@overload last(num)
@param num [Integer]
@return [self]
@return_single_parameter
)),
Override.from_comment('BasicObject#==', %(
@param other [BasicObject]
@return [Boolean]
)),
Override.method_return('Class#new', 'self'),
Override.method_return('Class.new', 'Class<Object>'),
Override.method_return('Class#allocate', 'self'),
Override.method_return('Class.allocate', 'Class<Object>'),
Override.method_return('Enumerable#select', 'self'),
Override.method_return('File.dirname', 'String'),
Override.from_comment('Hash#[]', %(
@return_value_parameter
)),
# @todo This override isn't robust enough. It needs to allow for
# parameterized Hash types, e.g., [Hash{Symbol => String}].
Override.from_comment('Hash#[]=', %(
@param_tuple
)),
Override.method_return('Object#!', 'Boolean'),
Override.method_return('Object#clone', 'self', delete: [:overload]),
Override.method_return('Object#dup', 'self'),
Override.method_return('Object#freeze', 'self', delete: [:overload]),
Override.method_return('Object#taint', 'self'),
Override.method_return('Object#to_s', 'String'),
Override.method_return('Object#untaint', 'self'),
Override.from_comment('Object#tap', %(
@return [self]
@yieldparam [self]
)),
Override.method_return('String#freeze', 'self'),
Override.method_return('String#split', 'Array<String>'),
Override.method_return('String#lines', 'Array<String>')
].concat(
methods_with_yieldparam_subtypes.map do |path|
Override.from_comment(path, %(
@yieldparam_single_parameter
))
end
)
end
end
| 30.649123 | 79 | 0.634516 |
33ee20ee54cb7f91a6d63d1911d6cdcb64aad0a9 | 1,533 | class Helmfile < Formula
desc "Deploy Kubernetes Helm Charts"
homepage "https://github.com/roboll/helmfile"
url "https://github.com/roboll/helmfile/archive/v0.81.0.tar.gz"
sha256 "6aba51fed66930fe7445570116daa9cdd7fb3a0fa73b4758f490efc6561e8e07"
bottle do
cellar :any_skip_relocation
sha256 "c07835bf5c7f685366c36416a10fae8b1925bc981baf106ef68d5eceb9d7df3d" => :mojave
sha256 "17505b135bbc1b03d2f0920a1769360560791cdbb546f96ae74928c0da628c49" => :high_sierra
sha256 "3abf9039c9660f44f6ff89c007ecaa3841444434284903819681f2262b57d248" => :sierra
end
depends_on "go" => :build
depends_on "kubernetes-helm"
def install
ENV["GOPATH"] = buildpath
ENV["GO111MODULE"] = "on"
(buildpath/"src/github.com/roboll/helmfile").install buildpath.children
cd "src/github.com/roboll/helmfile" do
system "go", "build", "-ldflags", "-X main.Version=v#{version}",
"-o", bin/"helmfile", "-v", "github.com/roboll/helmfile"
prefix.install_metafiles
end
end
test do
(testpath/"helmfile.yaml").write <<-EOS
repositories:
- name: stable
url: https://kubernetes-charts.storage.googleapis.com/
releases:
- name: test
EOS
system Formula["kubernetes-helm"].opt_bin/"helm", "init", "--client-only"
output = "Adding repo stable https://kubernetes-charts.storage.googleapis.com"
assert_match output, shell_output("#{bin}/helmfile -f helmfile.yaml repos 2>&1")
assert_match version.to_s, shell_output("#{bin}/helmfile -v")
end
end
| 34.840909 | 93 | 0.717547 |
e8a46db9c44fde487484895071cc9f013d994b0f | 148 | object @user => nil
node(:user) { partial 'users/show', object: @user } if @user
node(:token) { partial 'tokens/show', object: @token } if @token
| 29.6 | 64 | 0.655405 |
918c1f80f1cfec1067aa9a6e14a6629cd3babee0 | 202 | class CreateTickets < ActiveRecord::Migration
def change
create_table :tickets do |t|
t.belongs_to :event
t.integer :total
t.decimal :price
t.timestamps
end
end
end
| 16.833333 | 45 | 0.653465 |
1d3fb2c222f336413bfe2ea2c219876f713156ee | 30 | package 'the_silver_searcher'
| 15 | 29 | 0.866667 |
395fc8c0e99697fa4a1b71821266372fcaeed218 | 4,003 | module RewardsDoc
extend Apipie::DSL::Concern
extend BeachApiCore::Concerns::V1::ApipieResponseConcern
api :POST, '/rewards', 'Create new reward'
header 'Authorization', 'Bearer access_token', required: true
param :reward, Hash, required: true do
param :achievement_id, Integer, required: true
param :giftbit_brand_id, Integer, required: false, desc: "Required only for achievement with Giftbit mode"
end
example '
{
"reward": {
"id": 59,
"achievement_id": 18,
"confirmed": true,
"status": "Pending",
"created_at": "2019-01-22T12:59:14.621Z",
"giftbit_brand": {
"id": 7,
"giftbit_config_id": 4,
"gift_name": "$12 playstation Gift Card",
"amount": 500,
"brand_code": "walmart",
"giftbit_email_template": "Playstation_template_id",
"email_subject": "",
"email_body": ""
}
}
}'
def create; end
api :GET, '/rewards', 'Return all user\'s rewards'
header 'Authorization', 'Bearer access_token', required: true
example '
{
"rewards": [
{
"id": 54,
"achievement_id": 12,
"confirmed": true,
"status": "Pending",
"created_at": "2019-01-17T10:18:44.310Z"
},
{
"id": 55,
"achievement_id": 13,
"confirmed": true,
"status": "Pending",
"created_at": "2019-01-17T10:19:43.220Z",
"giftbit_brand": {
"id": 7,
"giftbit_config_id": 4,
"gift_name": "$5 Walmart Gift Card",
"amount": 500,
"brand_code": "walmart",
"giftbit_email_template": "Walmart_template_id",
"email_subject": "",
"email_body": ""
}
}
]
}'
def index; end
api :GET, '/rewards/:id', 'Return reward data'
header 'Authorization', 'Bearer access_token', required: true
example '
{
"reward": {
"id": 45,
"achievement_id": 9,
"confirmed": true,
"status": "Spent",
"created_at": "2019-01-14T11:38:38.127Z"
}
}'
def show; end
api :PUT, '/rewards/:id/confirm_reward', 'Confirm reward'
header 'Authorization', 'Bearer access_token', required: true
example '
{
"message": "Confirmed",
"reward": {
"id": 59,
"achievement_id": 18,
"confirmed": true,
"status": "Pending",
"created_at": "2019-01-22T12:59:14.621Z",
"giftbit_brand": {
"id": 7,
"giftbit_config_id": 4,
"gift_name": "$12 playstation Gift Card",
"amount": 500,
"brand_code": "walmart",
"giftbit_email_template": "Playstation_template_id",
"email_subject": "",
"email_body": ""
}
}
}'
def confirm_reward; end
api :PUT, '/rewards/resend_gift/:uuid', 'Resend Gift'
header 'Authorization', 'Bearer access_token', required: true
example '{
"message": "The gift has been resent.",
"status": 200
}'
def resend_gift; end
api :DELETE, '/rewards/cancel_gift/:uuid', 'Cancel Gift'
header 'Authorization', 'Bearer access_token', required: true
example '
{
"message": "The gift has been canceled.",
"reward": {
"id": 59,
"achievement_id": 18,
"confirmed": true,
"status": "Closed",
"created_at": "2019-01-22T12:59:14.621Z",
"gift_uuid": "f0c9b59a3f944a839937718b315899e6",
"shortlink": "http://gtbt.co/7zXFzDdWYWN",
"giftbit_brand": {
"id": 7,
"giftbit_config_id": 4,
"gift_name": "$12 playstation Gift Card",
"amount": 500,
"brand_code": "walmart",
"giftbit_email_template": "Playstation_template_id",
"email_subject": "",
"email_body": ""
}
},
"status": 200
}'
def cancel_gift; end
api :DELETE, '/rewards/:id', "Remove reward"
header 'Authorization', 'Bearer access_token', required: true
example '{
fail: "Could not remove reward"
}'
def destroy; end
end
| 26.865772 | 114 | 0.566575 |
aca7c8c4a89f21b20d3f6fd71e56db1f052cee85 | 383 | # Neil created this, designed around http://stackoverflow.com/questions/10088619/how-to-clear-rails-sessions-table
# hint: config/initializers/devise.rb sets "remember_for"
namespace :sessions do
desc 'Clear expired sessions from the database'
task cleanup: :environment do
ActiveRecord::SessionStore::Session.delete_all(['updated_at < ?', Devise.remember_for.ago])
end
end | 47.875 | 114 | 0.78329 |
3366b6996b431f9ed9ac01395c85fff7351b9c18 | 3,070 | module Salesfly
class MailAPI
SCHEMA = {
"type" => "object",
"properties" => {
"date" => {
"type" => "string",
"format" => "date-time"
},
"from" => {
"type" => "string",
"maxLength" => 50
},
"from_name" => {
"type" => "string",
"maxLength" => 50
},
"to" => {
"type" => "array",
"minLength" => 1,
"maxLength" => 50,
"items" => {
"type" => "string",
}
},
"cc" => {
"type" => "array",
"minLength" => 1,
"maxLength" => 50,
"items" => {
"type" => "string"
}
},
"bcc" => {
"type" => "array",
"minLength" => 1,
"maxLength" => 50,
"items" => {
"type" => "string"
}
},
"reply_to" => {
"type" => "string",
"maxLength" => 50
},
"subject" => {
"type" => "string",
"maxLength" => 100
},
"text" => {
"type" => "string"
},
"html" => {
"type" => "string"
},
"attachments" => {
"type" => "array",
"maxLength" => 10,
"items" => {
"type" => "string"
}
},
"tags" => {
"type" => "array",
"maxLength" => 3,
"items" => {
"type" => "string",
"maxLength" => 20,
}
},
"charset" => {
"type" => "string",
"maxLength" => 20
},
"encoding" => {
"type" => "string",
"maxLength" => 20
},
"require_tls" => {
"type" => "boolean"
},
"verify_cert" => {
"type" => "boolean"
},
"open_tracking" => {
"type" => "boolean"
},
"click_tracking" => {
"type" => "boolean"
},
"text_click_tracking" => {
"type" => "boolean"
},
"unsubscribe_tracking" => {
"type" => "boolean"
},
"test_mode" => {
"type" => "boolean"
}
},
"required" => ["from", "to", "subject", "text"],
"additionalProperties" => false
}
def initialize(rest_client)
@rest_client = rest_client
end
def send(message)
# Validate message
begin
JSON::Validator.validate!(SCHEMA, message, :strict => false)
rescue JSON::Schema::ValidationError => e
raise ArgumentError.new("Message has missing or invalid attributes")
end
# Extract files
files = []
if message.key?("attachments")
files = message["attachments"]
message = message.reject { |k,v| k == "attachments" }
end
multipart = Multipart.new
content, headers = multipart.encode(message, files)
return @rest_client.post("/v1/mail/send", content, headers)
end
end
end | 23.79845 | 76 | 0.382736 |
edd9b5ae7d029bcd3820429f5037df29a7a9d0dc | 18,747 | require 'spec_helper'
describe Bosh::AwsCloud::Cloud do
before { @tmp_dir = Dir.mktmpdir }
after { FileUtils.rm_rf(@tmp_dir) }
describe 'EBS-volume based flow' do
let(:creator) { double(Bosh::AwsCloud::StemcellCreator) }
let(:volume_manager) { instance_double(Bosh::AwsCloud::VolumeManager) }
let(:az_selector) do
instance_double(Bosh::AwsCloud::AvailabilityZoneSelector, select_availability_zone: 'us-east-1a')
end
let(:disk_config) do
{
size: 2,
availability_zone: 'us-east-1a',
volume_type: 'gp2',
encrypted: false
}
end
context 'light stemcell' do
let(:ami_id) { 'ami-xxxxxxxx' }
let(:encrypted_ami) { instance_double(Aws::EC2::Image, state: 'available') }
let(:stemcell_properties) do
{
'root_device_name' => '/dev/sda1',
'architecture' => 'x86_64',
'name' => 'stemcell-name',
'version' => '1.2.3',
'ami' => {
'us-east-1' => ami_id
}
}
end
it 'should return a light stemcell' do
cloud = mock_cloud do |ec2|
expect(ec2).to receive(:images).with(
filters: [{
name: 'image-id',
values: [ami_id],
}],
).and_return([double('image', id: ami_id)])
end
expect(cloud.create_stemcell('/tmp/foo', stemcell_properties)).to eq("#{ami_id} light")
end
context 'when encrypted flag is true' do
let(:kms_key_arn) { nil }
let(:stemcell_properties) do
{
'encrypted' => true,
'ami' => {
'us-east-1' => ami_id
}
}
end
it 'should copy ami' do
cloud = mock_cloud do |ec2|
expect(ec2).to receive(:images).with(
filters: [{
name: 'image-id',
values: [ami_id],
}],
).and_return([double('image', id: ami_id)])
expect(ec2.client).to receive(:copy_image).with(
source_region: 'us-east-1',
source_image_id: ami_id,
name: "Copied from SourceAMI #{ami_id}",
encrypted: true,
kms_key_id: kms_key_arn
).and_return(double('copy_image_result', image_id: 'ami-newami'))
expect(ec2).to receive(:image).with('ami-newami').and_return(encrypted_ami)
expect(Bosh::AwsCloud::ResourceWait).to receive(:for_image).with(
image: encrypted_ami,
state: 'available'
)
end
cloud.create_stemcell('/tmp/foo', stemcell_properties)
end
it 'should return stemcell id (not light stemcell id)' do
cloud = mock_cloud do |ec2, client|
expect(ec2).to receive(:images).with(
filters: [{
name: 'image-id',
values: [ami_id],
}],
).and_return([double('image', id: ami_id)])
expect(ec2.client).to receive(:copy_image).with(
source_region: 'us-east-1',
source_image_id: ami_id,
name: "Copied from SourceAMI #{ami_id}",
encrypted: true,
kms_key_id: kms_key_arn
).and_return(double('copy_image_result', image_id: 'ami-newami'))
expect(ec2).to receive(:image).with('ami-newami').and_return(encrypted_ami)
expect(Bosh::AwsCloud::ResourceWait).to receive(:for_image).with(
image: encrypted_ami,
state: 'available'
)
end
expect(cloud.create_stemcell('/tmp/foo', stemcell_properties)).to eq('ami-newami')
end
end
context 'and kms_key_arn is given' do
let(:kms_key_arn) { 'arn:aws:kms:us-east-1:12345678:key/guid' }
let(:stemcell_properties) do
{
'encrypted' => true,
'kms_key_arn' => kms_key_arn,
'ami' => {
'us-east-1' => ami_id
}
}
end
it 'should encrypt ami with given kms_key_arn' do
cloud = mock_cloud do |ec2, client|
expect(ec2).to receive(:images).with(
filters: [{
name: 'image-id',
values: [ami_id],
}],
).and_return([double('image', id: ami_id)])
expect(ec2.client).to receive(:copy_image).with(
source_region: 'us-east-1',
source_image_id: ami_id,
name: "Copied from SourceAMI #{ami_id}",
encrypted: true,
kms_key_id: kms_key_arn
).and_return(double('copy_image_result', image_id: 'ami-newami'))
expect(ec2).to receive(:image).with('ami-newami').and_return(encrypted_ami)
expect(Bosh::AwsCloud::ResourceWait).to receive(:for_image).with(
image: encrypted_ami,
state: 'available'
)
end
cloud.create_stemcell('/tmp/foo', stemcell_properties)
end
end
context 'when ami does NOT exist' do
it 'should return error' do
cloud = mock_cloud do |ec2|
allow(ec2).to receive(:images).with(
filters: [{
name: 'image-id',
values: ['ami-xxxxxxxx']
}]
).and_return([])
end
expect{
cloud.create_stemcell('/tmp/foo', stemcell_properties)
}.to raise_error(/Stemcell does not contain an AMI in region/)
end
end
end
context 'heavy stemcell' do
let(:stemcell_properties) do
{
'root_device_name' => '/dev/sda1',
'architecture' => 'x86_64',
'name' => 'stemcell-name',
'version' => '1.2.3',
'virtualization_type' => 'paravirtual'
}
end
let(:volume) { instance_double(Aws::EC2::Volume, :id => 'vol-xxxxxxxx') }
let(:stemcell) { instance_double(Bosh::AwsCloud::Stemcell, :id => 'ami-xxxxxxxx') }
let(:instance) { instance_double(Aws::EC2::Instance) }
let(:aws_config) do
instance_double(Bosh::AwsCloud::AwsConfig, stemcell: {}, encrypted: false, kms_key_arn: nil)
end
let(:global_config) { instance_double(Bosh::AwsCloud::Config, aws: aws_config) }
let(:stemcell_cloud_props) { Bosh::AwsCloud::StemcellCloudProps.new(stemcell_properties, global_config) }
let(:props_factory) { instance_double(Bosh::AwsCloud::PropsFactory) }
before do
allow(Bosh::AwsCloud::PropsFactory).to receive(:new)
.and_return(props_factory)
allow(props_factory).to receive(:stemcell_props)
.with(stemcell_properties)
.and_return(stemcell_cloud_props)
end
it 'should create a stemcell' do
cloud = mock_cloud do |ec2|
allow(ec2).to receive(:volume).with('vol-xxxxxxxx').and_return(volume)
allow(ec2).to receive(:instance).with('i-xxxxxxxx').and_return(instance)
expect(Bosh::AwsCloud::StemcellCreator).to receive(:new)
.with(ec2, stemcell_cloud_props)
.and_return(creator)
expect(Bosh::AwsCloud::VolumeManager).to receive(:new).and_return(volume_manager)
expect(Bosh::AwsCloud::AvailabilityZoneSelector).to receive(:new).and_return(az_selector)
end
allow(instance).to receive(:exists?).and_return(true)
allow(instance).to receive(:reload).and_return(instance)
allow(cloud).to receive(:current_vm_id).and_return('i-xxxxxxxx')
expect(volume_manager).to receive(:create_ebs_volume).with(disk_config).and_return(volume)
expect(volume_manager).to receive(:attach_ebs_volume).with(instance, volume).and_return('/dev/sdh')
expect(cloud).to receive(:find_device_path_by_name).with('/dev/sdh').and_return('ebs')
expect(creator).to receive(:create).with(volume, 'ebs', '/tmp/foo').and_return(stemcell)
expect(volume_manager).to receive(:detach_ebs_volume).with(instance, volume, true)
expect(volume_manager).to receive(:delete_ebs_volume).with(volume)
expect(cloud.create_stemcell('/tmp/foo', stemcell_properties)).to eq('ami-xxxxxxxx')
end
context 'when the CPI configuration includes a kernel_id for stemcell' do
it 'creates a stemcell' do
options = mock_cloud_options['properties']
options['aws']['stemcell'] = {'kernel_id' => 'fake-kernel-id'}
cloud = mock_cloud(options) do |ec2|
allow(ec2).to receive(:volume).with('vol-xxxxxxxx').and_return(volume)
allow(ec2).to receive(:instance).with('i-xxxxxxxx').and_return(instance)
stemcell_properties.merge('kernel_id' => 'fake-kernel-id')
expect(Bosh::AwsCloud::StemcellCreator).to receive(:new)
.with(ec2, stemcell_cloud_props)
.and_return(creator)
expect(Bosh::AwsCloud::VolumeManager).to receive(:new).and_return(volume_manager)
expect(Bosh::AwsCloud::AvailabilityZoneSelector).to receive(:new).and_return(az_selector)
end
allow(instance).to receive(:exists?).and_return(true)
allow(instance).to receive(:reload).and_return(instance)
allow(cloud).to receive(:current_vm_id).and_return('i-xxxxxxxx')
expect(volume_manager).to receive(:create_ebs_volume).with(disk_config).and_return(volume)
expect(volume_manager).to receive(:attach_ebs_volume).with(instance, volume).and_return('/dev/sdh')
expect(cloud).to receive(:find_device_path_by_name).with('/dev/sdh').and_return('ebs')
allow(creator).to receive(:create)
expect(creator).to receive(:create).with(volume, 'ebs', '/tmp/foo').and_return(stemcell)
expect(volume_manager).to receive(:detach_ebs_volume).with(instance, volume, true)
expect(volume_manager).to receive(:delete_ebs_volume).with(volume)
expect(cloud.create_stemcell('/tmp/foo', stemcell_properties)).to eq('ami-xxxxxxxx')
end
end
context 'when encrypted flag is set to true' do
context 'and kms_key_arn is provided' do
let(:stemcell_properties) do
{
'root_device_name' => '/dev/sda1',
'architecture' => 'x86_64',
'name' => 'stemcell-name',
'version' => '1.2.3',
'virtualization_type' => 'paravirtual',
'encrypted' => true,
'kms_key_arn' => 'arn:aws:kms:us-east-1:ID:key/GUID'
}
end
let(:disk_config) do
{
size: 2,
availability_zone: 'us-east-1a',
volume_type: 'gp2',
encrypted: true,
kms_key_id: 'arn:aws:kms:us-east-1:ID:key/GUID'
}
end
it 'should create stemcell with encrypted disk with the given kms key' do
cloud = mock_cloud do |ec2|
allow(ec2).to receive(:volume).with('vol-xxxxxxxx').and_return(volume)
allow(ec2).to receive(:instance).with('i-xxxxxxxx').and_return(instance)
expect(Bosh::AwsCloud::StemcellCreator).to receive(:new)
.with(ec2, stemcell_cloud_props)
.and_return(creator)
expect(Bosh::AwsCloud::VolumeManager).to receive(:new).and_return(volume_manager)
expect(Bosh::AwsCloud::AvailabilityZoneSelector).to receive(:new).and_return(az_selector)
end
allow(instance).to receive(:exists?).and_return(true)
allow(instance).to receive(:reload).and_return(instance)
allow(cloud).to receive(:current_vm_id).and_return('i-xxxxxxxx')
expect(volume_manager).to receive(:create_ebs_volume).with(disk_config).and_return(volume)
expect(volume_manager).to receive(:attach_ebs_volume).with(instance, volume).and_return('/dev/sdh')
expect(cloud).to receive(:find_device_path_by_name).with('/dev/sdh').and_return('ebs')
expect(creator).to receive(:create).with(volume, 'ebs', '/tmp/foo').and_return(stemcell)
expect(volume_manager).to receive(:detach_ebs_volume).with(instance, volume, true)
expect(volume_manager).to receive(:delete_ebs_volume).with(volume)
expect(cloud.create_stemcell('/tmp/foo', stemcell_properties)).to eq('ami-xxxxxxxx')
end
end
context 'and kms_key_arn is NOT provided' do
let(:stemcell_properties) do
{
'root_device_name' => '/dev/sda1',
'architecture' => 'x86_64',
'name' => 'stemcell-name',
'version' => '1.2.3',
'virtualization_type' => 'paravirtual',
'encrypted' => true
}
end
let(:disk_config) do
{
size: 2,
availability_zone: 'us-east-1a',
volume_type: 'gp2',
encrypted: true
}
end
it 'should create stemcell with encrypted disk' do
cloud = mock_cloud do |ec2|
allow(ec2).to receive(:volume).with('vol-xxxxxxxx').and_return(volume)
allow(ec2).to receive(:instance).with('i-xxxxxxxx').and_return(instance)
expect(Bosh::AwsCloud::StemcellCreator).to receive(:new)
.with(ec2, stemcell_cloud_props)
.and_return(creator)
expect(Bosh::AwsCloud::VolumeManager).to receive(:new).and_return(volume_manager)
expect(Bosh::AwsCloud::AvailabilityZoneSelector).to receive(:new).and_return(az_selector)
end
allow(instance).to receive(:exists?).and_return(true)
allow(instance).to receive(:reload).and_return(instance)
allow(cloud).to receive(:current_vm_id).and_return('i-xxxxxxxx')
expect(volume_manager).to receive(:create_ebs_volume).with(disk_config).and_return(volume)
expect(volume_manager).to receive(:attach_ebs_volume).with(instance, volume).and_return('/dev/sdh')
expect(cloud).to receive(:find_device_path_by_name).with('/dev/sdh').and_return('ebs')
expect(creator).to receive(:create).with(volume, 'ebs', '/tmp/foo').and_return(stemcell)
expect(volume_manager).to receive(:detach_ebs_volume).with(instance, volume, true)
expect(volume_manager).to receive(:delete_ebs_volume).with(volume)
expect(cloud.create_stemcell('/tmp/foo', stemcell_properties)).to eq('ami-xxxxxxxx')
end
end
end
context 'when encryption information is incomplete' do
def test_for_unencrypted_root_disk()
cloud = mock_cloud do |ec2|
allow(ec2).to receive(:volume).with('vol-xxxxxxxx').and_return(volume)
allow(ec2).to receive(:instance).with('i-xxxxxxxx').and_return(instance)
expect(Bosh::AwsCloud::StemcellCreator).to receive(:new)
.with(ec2, stemcell_cloud_props)
.and_return(creator)
expect(Bosh::AwsCloud::VolumeManager).to receive(:new).and_return(volume_manager)
expect(Bosh::AwsCloud::AvailabilityZoneSelector).to receive(:new).and_return(az_selector)
end
allow(instance).to receive(:exists?).and_return(true)
allow(instance).to receive(:reload).and_return(instance)
allow(cloud).to receive(:current_vm_id).and_return('i-xxxxxxxx')
expect(volume_manager).to receive(:create_ebs_volume).with(disk_config).and_return(volume)
expect(volume_manager).to receive(:attach_ebs_volume).with(instance, volume).and_return('/dev/sdh')
expect(cloud).to receive(:find_device_path_by_name).with('/dev/sdh').and_return('ebs')
expect(creator).to receive(:create).with(volume, 'ebs', '/tmp/foo').and_return(stemcell)
expect(volume_manager).to receive(:detach_ebs_volume).with(instance, volume, true)
expect(volume_manager).to receive(:delete_ebs_volume).with(volume)
expect(cloud.create_stemcell('/tmp/foo', stemcell_properties)).to eq('ami-xxxxxxxx')
end
let(:disk_config) do
{
size: 2,
availability_zone: 'us-east-1a',
volume_type: 'gp2',
encrypted: false,
kms_key_id: 'arn:aws:kms:us-east-1:ID:key/GUID'
}
end
context 'when `encrypted` is false and kms_key_arn is provided' do
let(:stemcell_properties) do
{
'root_device_name' => '/dev/sda1',
'architecture' => 'x86_64',
'name' => 'stemcell-name',
'version' => '1.2.3',
'virtualization_type' => 'paravirtual',
'encrypted' => false,
'kms_key_arn' => 'arn:aws:kms:us-east-1:ID:key/GUID'
}
end
it 'should create an unencrypted stemcell' do
test_for_unencrypted_root_disk
end
end
context 'when `encrypted` is missing and kms_key_arn is provided' do
let(:stemcell_properties) do
{
'root_device_name' => '/dev/sda1',
'architecture' => 'x86_64',
'name' => 'stemcell-name',
'version' => '1.2.3',
'virtualization_type' => 'paravirtual',
'kms_key_arn' => 'arn:aws:kms:us-east-1:ID:key/GUID'
}
end
it 'should create an unencrypted stemcell' do
test_for_unencrypted_root_disk
end
end
end
describe '#find_device_path_by_name' do
it 'should locate ebs volume on the current instance and return the device name' do
cloud = mock_cloud
allow(File).to receive(:blockdev?).with('/dev/sdf').and_return(true)
expect(cloud.send(:find_device_path_by_name, '/dev/sdf')).to eq('/dev/sdf')
end
it 'should locate ebs volume on the current instance and return the virtual device name' do
cloud = mock_cloud
allow(File).to receive(:blockdev?).with('/dev/sdf').and_return(false)
allow(File).to receive(:blockdev?).with('/dev/xvdf').and_return(true)
expect(cloud.send(:find_device_path_by_name, '/dev/sdf')).to eq('/dev/xvdf')
end
end
end
end
end
| 40.577922 | 111 | 0.579879 |
33289f79e0069312caec44d636909806ca0d952b | 837 | module Intrigue
module Ident
module Check
class DanneoCMS < Intrigue::Ident::Check::Base
def generate_checks(url)
[
{
:type => "fingerprint",
:category => "application",
:tags => ["CMS"],
:vendor => "Danneo",
:product => "Danneo",
:references => ["http://danneo.ru/"],
:match_details => "Danneo - generator page reference",
:version => nil,
:match_type => :content_body,
:match_content => /<meta name="generator" content="CMS Danneo/i,
:dynamic_version => lambda {
|x| _first_body_capture(x, /<meta name="generator" content="CMS Danneo (\d+(\.\d+)*)/i)
},
:hide => false,
:paths => [ { :path => "#{url}", :follow_redirects => true } ],
:inference => true
}
]
end
end
end
end
end
| 25.363636 | 97 | 0.535245 |
614d430648dd1da317474245db31c72c361c3f55 | 406 | require 'java'
module RedStorm
module Loggable
def self.included(clazz)
clazz.send(:extend, ClassMethods)
clazz.send(:include, InstanceMethods)
end
module ClassMethods
def log
@log ||= Java::OrgSlf4j::LoggerFactory.get_logger(self.name.gsub(/::/, '.'))
end
end
module InstanceMethods
def log
self.class.log
end
end
end
end
| 17.652174 | 84 | 0.618227 |
b97577a5b24fa9d1171ff782a53aac1ebe229ff0 | 644 | # Copyright (c) 2021 Target Brands, Inc. All rights reserved.
#
# Use of this source code is governed by the LICENSE file in this repository.
require 'formula'
class VelaAT03 < Formula
# repository information
head "https://github.com/go-vela/cli.git"
homepage 'https://github.com/go-vela/cli'
# utility information
version 'v0.3.0'
url "#{homepage}/releases/download/#{version}/vela_darwin_amd64.tar.gz"
sha256 '7065cda415b2cdd9b28252cd48723b42b8efa52ca2e052176aa9ddfbeb5af01b'
# install information
def install
bin.install 'vela'
end
# test information
test do
system "#{bin}/vela", "--version"
end
end
| 23.851852 | 77 | 0.729814 |
267828645b9539d6f480837f10d45e1af80f5ba2 | 4,469 | # == Schema Information
#
# Table name: dogs
#
# id :integer not null, primary key
# name :string(255)
# created_at :datetime
# updated_at :datetime
# tracking_id :integer
# primary_breed_id :integer
# secondary_breed_id :integer
# status :string(255)
# age :string(75)
# size :string(75)
# is_altered :boolean
# gender :string(6)
# is_special_needs :boolean
# no_dogs :boolean
# no_cats :boolean
# no_kids :boolean
# description :text
# foster_id :integer
# adoption_date :date
# is_uptodateonshots :boolean default(TRUE)
# intake_dt :date
# available_on_dt :date
# has_medical_need :boolean default(FALSE)
# is_high_priority :boolean default(FALSE)
# needs_photos :boolean default(FALSE)
# has_behavior_problem :boolean default(FALSE)
# needs_foster :boolean default(FALSE)
# petfinder_ad_url :string(255)
# craigslist_ad_url :string(255)
# youtube_video_url :string(255)
# first_shots :string(255)
# second_shots :string(255)
# third_shots :string(255)
# rabies :string(255)
# vac_4dx :string(255)
# bordetella :string(255)
# microchip :string(255)
# original_name :string(255)
# fee :integer
# coordinator_id :integer
# sponsored_by :string(255)
# shelter_id :integer
# medical_summary :text
# heartworm_preventative :string
# flea_tick_preventative :string
# medical_review_complete :boolean default(FALSE)
# behavior_summary :text
#
require 'rails_helper'
describe Dog do
describe '.update_adoption_date' do
# tests for the update_adoption_date callback simply document the behaviour found in the code
# without understanding the intent or validating correctness
let(:dog) { create(:dog, :adoptable) }
context 'status did not change' do
it 'does not update the date if none is provided' do
old_date = dog.adoption_date
dog.update_attribute(:name, "new_#{dog.name}")
expect(dog.adoption_date).to eq(old_date)
end
it 'updates the date to the value provided ' do
dog.update_attribute(:adoption_date, '2024-8-19')
expect(dog.adoption_date).to eq(Date.new(2024,8,19))
end
end
context 'status changed to completed' do
it 'does not update the date' do
old_date = dog.adoption_date
dog.update_attribute(:status, 'completed')
expect(dog.adoption_date).to eq(old_date)
end
it 'updates the adoption date if one is provided by the user' do
dog.update_attributes(status: 'completed', adoption_date: Date.new(2000,1,1))
expect(dog.adoption_date).to eq(Date.new(2000,1,1))
end
end
context 'status changed to adopted' do
it 'updates the date' do
dog.update_attribute(:status, 'adopted')
expect(dog.adoption_date).to eq(Date.today())
end
end
context 'status changed to value that is not complete or adopted' do
it 'updates the date to nil' do
dog.update_attribute(:status, 'adopted')
expect(dog.adoption_date).to eq(Date.today)
dog.update_attribute(:status, 'adoptable')
expect(dog.adoption_date).to be_nil
end
end
end
describe 'matching_tracking_id scope' do
let!(:good_dog){ create(:dog, tracking_id: 55) }
let!(:bad_dog){ create(:dog, tracking_id: 77) }
it 'result includes only matching tracking_id' do
dogs = Dog.search(['55','tracking_id'])
expect(dogs.length).to eq 1
expect(dogs).to include(good_dog)
expect(dogs).not_to include(bad_dog)
end
end
describe 'matches_microchip scope' do
let!(:good_dog){ create(:dog, microchip: 55) }
let!(:bad_dog){ create(:dog, microchip: 77) }
it 'result includes only matching tracking_id' do
dogs = Dog.search(['55','microchip'])
expect(dogs.length).to eq 1
expect(dogs).to include(good_dog)
expect(dogs).not_to include(bad_dog)
end
end
end
| 34.114504 | 97 | 0.597225 |
e938da7742c7e8ccbc76dc08169fa1e46be14162 | 12,303 | # The first thing you need to configure is which modules you need in your app.
# The default is nothing which will include only core features (password encryption, login/logout).
# Available submodules are: :user_activation, :http_basic_auth, :remember_me,
# :reset_password, :session_timeout, :brute_force_protection, :activity_logging, :external
# NOTE: Taken out external, remember_me
Rails.application.config.sorcery.submodules = [:core, :http_basic_auth, :reset_password, :activity_logging, :brute_force_protection, :user_activation, :session_timeout]
# Here you can configure each submodule's features.
Rails.application.config.sorcery.configure do |config|
# -- core --
# What controller action to call for non-authenticated users. You can also
# override the 'not_authenticated' method of course.
# Default: `:not_authenticated`
#
# config.not_authenticated_action =
# When a non logged in user tries to enter a page that requires login, save
# the URL he wanted to reach, and send him there after login, using 'redirect_back_or_to'.
# Default: `true`
#
# config.save_return_to_url =
# Set domain option for cookies; Useful for remember_me submodule.
# Default: `nil`
#
# config.cookie_domain =
# -- session timeout --
# How long in seconds to keep the session alive.
# Default: `3600`
#
# config.session_timeout =
# Use the last action as the beginning of session timeout.
# Default: `false`
#
# config.session_timeout_from_last_action =
# -- http_basic_auth --
# What realm to display for which controller name. For example {"My App" => "Application"}
# Default: `{"application" => "Application"}`
#
# config.controller_to_realm_map =
# -- activity logging --
# will register the time of last user login, every login.
# Default: `true`
#
# config.register_login_time =
# will register the time of last user logout, every logout.
# Default: `true`
#
# config.register_logout_time =
# will register the time of last user action, every action.
# Default: `true`
#
# config.register_last_activity_time =
# -- external --
# What providers are supported by this app, i.e. [:twitter, :facebook, :github, :linkedin, :xing, :google, :liveid] .
# Default: `[]`
#
# config.external_providers =
# You can change it by your local ca_file. i.e. '/etc/pki/tls/certs/ca-bundle.crt'
# Path to ca_file. By default use a internal ca-bundle.crt.
# Default: `'path/to/ca_file'`
#
# config.ca_file =
# For information about LinkedIn API:
# - user info fields go to https://developer.linkedin.com/documents/profile-fields
# - access permissions go to https://developer.linkedin.com/documents/authentication#granting
#
# config.linkedin.key = ""
# config.linkedin.secret = ""
# config.linkedin.callback_url = "http://0.0.0.0:3000/oauth/callback?provider=linkedin"
# config.linkedin.user_info_fields = ['first-name', 'last-name']
# config.linkedin.user_info_mapping = {first_name: "firstName", last_name: "lastName"}
# config.linkedin.access_permissions = ['r_basicprofile']
#
#
# For information about XING API:
# - user info fields go to https://dev.xing.com/docs/get/users/me
#
# config.xing.key = ""
# config.xing.secret = ""
# config.xing.callback_url = "http://0.0.0.0:3000/oauth/callback?provider=xing"
# config.xing.user_info_mapping = {first_name: "first_name", last_name: "last_name"}
#
#
# Twitter wil not accept any requests nor redirect uri containing localhost,
# make sure you use 0.0.0.0:3000 to access your app in development
#
# config.twitter.key = ""
# config.twitter.secret = ""
# config.twitter.callback_url = "http://0.0.0.0:3000/oauth/callback?provider=twitter"
# config.twitter.user_info_mapping = {:email => "screen_name"}
#
# config.facebook.key = ""
# config.facebook.secret = ""
# config.facebook.callback_url = "http://0.0.0.0:3000/oauth/callback?provider=facebook"
# config.facebook.user_info_mapping = {:email => "name"}
# config.facebook.access_permissions = ["email", "publish_stream"]
#
# config.github.key = ""
# config.github.secret = ""
# config.github.callback_url = "http://0.0.0.0:3000/oauth/callback?provider=github"
# config.github.user_info_mapping = {:email => "name"}
#
# config.google.key = ""
# config.google.secret = ""
# config.google.callback_url = "http://0.0.0.0:3000/oauth/callback?provider=google"
# config.google.user_info_mapping = {:email => "email", :username => "name"}
#
# config.vk.key = ""
# config.vk.secret = ""
# config.vk.callback_url = "http://0.0.0.0:3000/oauth/callback?provider=vk"
# config.vk.user_info_mapping = {:login => "domain", :name => "full_name"}
#
# To use liveid in development mode you have to replace mydomain.com with
# a valid domain even in development. To use a valid domain in development
# simply add your domain in your /etc/hosts file in front of 127.0.0.1
#
# config.liveid.key = ""
# config.liveid.secret = ""
# config.liveid.callback_url = "http://mydomain.com:3000/oauth/callback?provider=liveid"
# config.liveid.user_info_mapping = {:username => "name"}
# --- user config ---
config.user_config do |user|
# -- core --
# specify username attributes, for example: [:username, :email].
# Default: `[:username]`
#
user.username_attribute_names = [:email]
# change *virtual* password attribute, the one which is used until an encrypted one is generated.
# Default: `:password`
#
# user.password_attribute_name =
# downcase the username before trying to authenticate, default is false
# Default: `false`
#
user.downcase_username_before_authenticating = true
# change default email attribute.
# Default: `:email`
#
# user.email_attribute_name =
# change default crypted_password attribute.
# Default: `:crypted_password`
#
# user.crypted_password_attribute_name =
# what pattern to use to join the password with the salt
# Default: `""`
#
# user.salt_join_token =
# change default salt attribute.
# Default: `:salt`
#
# user.salt_attribute_name =
# how many times to apply encryption to the password.
# Default: `nil`
#
# user.stretches =
# encryption key used to encrypt reversible encryptions such as AES256.
# WARNING: If used for users' passwords, changing this key will leave passwords undecryptable!
# Default: `nil`
#
# user.encryption_key =
# use an external encryption class.
# Default: `nil`
#
# user.custom_encryption_provider =
# encryption algorithm name. See 'encryption_algorithm=' for available options.
# Default: `:bcrypt`
#
# user.encryption_algorithm =
# make this configuration inheritable for subclasses. Useful for ActiveRecord's STI.
# Default: `false`
#
# user.subclasses_inherit_config =
# -- remember_me --
# allow the remember_me cookie to settable through AJAX
# Default: `true`
#
# user.remember_me_httponly =
# How long in seconds the session length will be
# Default: `604800`
#
# user.remember_me_for =
# -- user_activation --
# the attribute name to hold activation state (active/pending).
# Default: `:activation_state`
#
# user.activation_state_attribute_name =
# the attribute name to hold activation code (sent by email).
# Default: `:activation_token`
#
# user.activation_token_attribute_name =
# the attribute name to hold activation code expiration date.
# Default: `:activation_token_expires_at`
#
# user.activation_token_expires_at_attribute_name =
# how many seconds before the activation code expires. nil for never expires.
# Default: `nil`
#
# user.activation_token_expiration_period =
# your mailer class. Required.
# Default: `nil`
#
user.user_activation_mailer = UserMailer
# when true sorcery will not automatically
# email activation details and allow you to
# manually handle how and when email is sent.
# Default: `false`
#
# user.activation_mailer_disabled = true
# activation needed email method on your mailer class.
# Default: `:activation_needed_email`
#
# user.activation_needed_email_method_name =
# activation success email method on your mailer class.
# Default: `:activation_success_email`
#
user.activation_success_email_method_name = nil
# do you want to prevent or allow users that did not activate by email to login?
# Default: `true`
#
# user.prevent_non_active_users_to_login =
# -- reset_password --
# reset password code attribute name.
# Default: `:reset_password_token`
#
# user.reset_password_token_attribute_name =
# expires at attribute name.
# Default: `:reset_password_token_expires_at`
#
# user.reset_password_token_expires_at_attribute_name =
# when was email sent, used for hammering protection.
# Default: `:reset_password_email_sent_at`
#
# user.reset_password_email_sent_at_attribute_name =
# mailer class. Needed.
# Default: `nil`
#
user.reset_password_mailer = UserMailer
# reset password email method on your mailer class.
# Default: `:reset_password_email`
#
# user.reset_password_email_method_name =
# when true sorcery will not automatically
# email password reset details and allow you to
# manually handle how and when email is sent
# Default: `false`
#
# user.reset_password_mailer_disabled =
# how many seconds before the reset request expires. nil for never expires.
# Default: `nil`
#
# user.reset_password_expiration_period =
# hammering protection, how long to wait before allowing another email to be sent.
# Default: `5 * 60`
#
# user.reset_password_time_between_emails =
# -- brute_force_protection --
# Failed logins attribute name.
# Default: `:failed_logins_count`
#
# user.failed_logins_count_attribute_name =
# This field indicates whether user is banned and when it will be active again.
# Default: `:lock_expires_at`
#
# user.lock_expires_at_attribute_name =
# How many failed logins allowed.
# Default: `50`
#
# user.consecutive_login_retries_amount_limit =
# How long the user should be banned. in seconds. 0 for permanent.
# Default: `60 * 60`
#
# user.login_lock_time_period =
# Unlock token attribute name
# Default: `:unlock_token`
#
# user.unlock_token_attribute_name =
# Unlock token mailer method
# Default: `:send_unlock_token_email`
#
# user.unlock_token_email_method_name =
# when true sorcery will not automatically
# send email with unlock token
# Default: `false`
#
# user.unlock_token_mailer_disabled = true
# Unlock token mailer class
# Default: `nil`
#
user.unlock_token_mailer = UserMailer
# -- activity logging --
# Last login attribute name.
# Default: `:last_login_at`
#
# user.last_login_at_attribute_name =
# Last logout attribute name.
# Default: `:last_logout_at`
#
# user.last_logout_at_attribute_name =
# Last activity attribute name.
# Default: `:last_activity_at`
#
# user.last_activity_at_attribute_name =
# How long since last activity is he user defined logged out?
# Default: `10 * 60`
#
user.activity_timeout = 7200
# -- external --
# Class which holds the various external provider data for this user.
# Default: `nil`
#
# user.authentications_class =
# User's identifier in authentications class.
# Default: `:user_id`
#
# user.authentications_user_id_attribute_name =
# Provider's identifier in authentications class.
# Default: `:provider`
#
# user.provider_attribute_name =
# User's external unique identifier in authentications class.
# Default: `:uid`
#
# user.provider_uid_attribute_name =
end
# This line must come after the 'user config' block.
# Define which model authenticates with sorcery.
config.user_class = "User"
end
| 28.025057 | 168 | 0.682842 |
39370559f952a62624b94cf87bb1b54b4cf69627 | 985 | require File.expand_path('../boot', __FILE__)
require 'rails/all'
# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(:default, Rails.env)
module NightOwl
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
end
end
| 41.041667 | 99 | 0.722843 |
79c8d79be35d663df9242900b5c3c37e80a28935 | 186 | project 'pe-bolt-server-runtime-2019.0.x' do |proj|
proj.setting(:pe_version, '2019.0')
instance_eval File.read(File.join(File.dirname(__FILE__), '_shared-pe-bolt-server.rb'))
end
| 26.571429 | 89 | 0.731183 |
87e2c1c8f5c42eb217e9740f70f75378ea08356d | 25,012 | # encoding: utf-8
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
module Azure::SQL::Mgmt::V2018_06_01_preview
#
# The Azure SQL Database management API provides a RESTful set of web APIs
# that interact with Azure SQL Database services to manage your databases.
# The API enables users to create, retrieve, update, and delete databases,
# servers, and other entities.
#
class ServerVulnerabilityAssessments
include MsRestAzure
#
# Creates and initializes a new instance of the ServerVulnerabilityAssessments class.
# @param client service class for accessing basic functionality.
#
def initialize(client)
@client = client
end
# @return [SqlManagementClient] reference to the SqlManagementClient
attr_reader :client
#
# Gets the server's vulnerability assessment.
#
# @param resource_group_name [String] The name of the resource group that
# contains the resource. You can obtain this value from the Azure Resource
# Manager API or the portal.
# @param server_name [String] The name of the server for which the
# vulnerability assessment is defined.
# @param custom_headers [Hash{String => String}] A hash of custom headers that
# will be added to the HTTP request.
#
# @return [ServerVulnerabilityAssessment] operation results.
#
def get(resource_group_name, server_name, custom_headers:nil)
response = get_async(resource_group_name, server_name, custom_headers:custom_headers).value!
response.body unless response.nil?
end
#
# Gets the server's vulnerability assessment.
#
# @param resource_group_name [String] The name of the resource group that
# contains the resource. You can obtain this value from the Azure Resource
# Manager API or the portal.
# @param server_name [String] The name of the server for which the
# vulnerability assessment is defined.
# @param custom_headers [Hash{String => String}] A hash of custom headers that
# will be added to the HTTP request.
#
# @return [MsRestAzure::AzureOperationResponse] HTTP response information.
#
def get_with_http_info(resource_group_name, server_name, custom_headers:nil)
get_async(resource_group_name, server_name, custom_headers:custom_headers).value!
end
#
# Gets the server's vulnerability assessment.
#
# @param resource_group_name [String] The name of the resource group that
# contains the resource. You can obtain this value from the Azure Resource
# Manager API or the portal.
# @param server_name [String] The name of the server for which the
# vulnerability assessment is defined.
# @param [Hash{String => String}] A hash of custom headers that will be added
# to the HTTP request.
#
# @return [Concurrent::Promise] Promise object which holds the HTTP response.
#
def get_async(resource_group_name, server_name, custom_headers:nil)
fail ArgumentError, 'resource_group_name is nil' if resource_group_name.nil?
fail ArgumentError, 'server_name is nil' if server_name.nil?
vulnerability_assessment_name = 'default'
fail ArgumentError, '@client.subscription_id is nil' if @client.subscription_id.nil?
fail ArgumentError, '@client.api_version is nil' if @client.api_version.nil?
request_headers = {}
request_headers['Content-Type'] = 'application/json; charset=utf-8'
# Set Headers
request_headers['x-ms-client-request-id'] = SecureRandom.uuid
request_headers['accept-language'] = @client.accept_language unless @client.accept_language.nil?
path_template = 'subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/servers/{serverName}/vulnerabilityAssessments/{vulnerabilityAssessmentName}'
request_url = @base_url || @client.base_url
options = {
middlewares: [[MsRest::RetryPolicyMiddleware, times: 3, retry: 0.02], [:cookie_jar]],
path_params: {'resourceGroupName' => resource_group_name,'serverName' => server_name,'vulnerabilityAssessmentName' => vulnerability_assessment_name,'subscriptionId' => @client.subscription_id},
query_params: {'api-version' => @client.api_version},
headers: request_headers.merge(custom_headers || {}),
base_url: request_url
}
promise = @client.make_request_async(:get, path_template, options)
promise = promise.then do |result|
http_response = result.response
status_code = http_response.status
response_content = http_response.body
unless status_code == 200
error_model = JSON.load(response_content)
fail MsRestAzure::AzureOperationError.new(result.request, http_response, error_model)
end
result.request_id = http_response['x-ms-request-id'] unless http_response['x-ms-request-id'].nil?
# Deserialize Response
if status_code == 200
begin
parsed_response = response_content.to_s.empty? ? nil : JSON.load(response_content)
result_mapper = Azure::SQL::Mgmt::V2018_06_01_preview::Models::ServerVulnerabilityAssessment.mapper()
result.body = @client.deserialize(result_mapper, parsed_response)
rescue Exception => e
fail MsRest::DeserializationError.new('Error occurred in deserializing the response', e.message, e.backtrace, result)
end
end
result
end
promise.execute
end
#
# Creates or updates the server's vulnerability assessment.
#
# @param resource_group_name [String] The name of the resource group that
# contains the resource. You can obtain this value from the Azure Resource
# Manager API or the portal.
# @param server_name [String] The name of the server for which the
# vulnerability assessment is defined.
# @param parameters [ServerVulnerabilityAssessment] The requested resource.
# @param custom_headers [Hash{String => String}] A hash of custom headers that
# will be added to the HTTP request.
#
# @return [ServerVulnerabilityAssessment] operation results.
#
def create_or_update(resource_group_name, server_name, parameters, custom_headers:nil)
response = create_or_update_async(resource_group_name, server_name, parameters, custom_headers:custom_headers).value!
response.body unless response.nil?
end
#
# Creates or updates the server's vulnerability assessment.
#
# @param resource_group_name [String] The name of the resource group that
# contains the resource. You can obtain this value from the Azure Resource
# Manager API or the portal.
# @param server_name [String] The name of the server for which the
# vulnerability assessment is defined.
# @param parameters [ServerVulnerabilityAssessment] The requested resource.
# @param custom_headers [Hash{String => String}] A hash of custom headers that
# will be added to the HTTP request.
#
# @return [MsRestAzure::AzureOperationResponse] HTTP response information.
#
def create_or_update_with_http_info(resource_group_name, server_name, parameters, custom_headers:nil)
create_or_update_async(resource_group_name, server_name, parameters, custom_headers:custom_headers).value!
end
#
# Creates or updates the server's vulnerability assessment.
#
# @param resource_group_name [String] The name of the resource group that
# contains the resource. You can obtain this value from the Azure Resource
# Manager API or the portal.
# @param server_name [String] The name of the server for which the
# vulnerability assessment is defined.
# @param parameters [ServerVulnerabilityAssessment] The requested resource.
# @param [Hash{String => String}] A hash of custom headers that will be added
# to the HTTP request.
#
# @return [Concurrent::Promise] Promise object which holds the HTTP response.
#
def create_or_update_async(resource_group_name, server_name, parameters, custom_headers:nil)
fail ArgumentError, 'resource_group_name is nil' if resource_group_name.nil?
fail ArgumentError, 'server_name is nil' if server_name.nil?
vulnerability_assessment_name = 'default'
fail ArgumentError, 'parameters is nil' if parameters.nil?
fail ArgumentError, '@client.subscription_id is nil' if @client.subscription_id.nil?
fail ArgumentError, '@client.api_version is nil' if @client.api_version.nil?
request_headers = {}
request_headers['Content-Type'] = 'application/json; charset=utf-8'
# Set Headers
request_headers['x-ms-client-request-id'] = SecureRandom.uuid
request_headers['accept-language'] = @client.accept_language unless @client.accept_language.nil?
# Serialize Request
request_mapper = Azure::SQL::Mgmt::V2018_06_01_preview::Models::ServerVulnerabilityAssessment.mapper()
request_content = @client.serialize(request_mapper, parameters)
request_content = request_content != nil ? JSON.generate(request_content, quirks_mode: true) : nil
path_template = 'subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/servers/{serverName}/vulnerabilityAssessments/{vulnerabilityAssessmentName}'
request_url = @base_url || @client.base_url
options = {
middlewares: [[MsRest::RetryPolicyMiddleware, times: 3, retry: 0.02], [:cookie_jar]],
path_params: {'resourceGroupName' => resource_group_name,'serverName' => server_name,'vulnerabilityAssessmentName' => vulnerability_assessment_name,'subscriptionId' => @client.subscription_id},
query_params: {'api-version' => @client.api_version},
body: request_content,
headers: request_headers.merge(custom_headers || {}),
base_url: request_url
}
promise = @client.make_request_async(:put, path_template, options)
promise = promise.then do |result|
http_response = result.response
status_code = http_response.status
response_content = http_response.body
unless status_code == 200 || status_code == 201
error_model = JSON.load(response_content)
fail MsRestAzure::AzureOperationError.new(result.request, http_response, error_model)
end
result.request_id = http_response['x-ms-request-id'] unless http_response['x-ms-request-id'].nil?
# Deserialize Response
if status_code == 200
begin
parsed_response = response_content.to_s.empty? ? nil : JSON.load(response_content)
result_mapper = Azure::SQL::Mgmt::V2018_06_01_preview::Models::ServerVulnerabilityAssessment.mapper()
result.body = @client.deserialize(result_mapper, parsed_response)
rescue Exception => e
fail MsRest::DeserializationError.new('Error occurred in deserializing the response', e.message, e.backtrace, result)
end
end
# Deserialize Response
if status_code == 201
begin
parsed_response = response_content.to_s.empty? ? nil : JSON.load(response_content)
result_mapper = Azure::SQL::Mgmt::V2018_06_01_preview::Models::ServerVulnerabilityAssessment.mapper()
result.body = @client.deserialize(result_mapper, parsed_response)
rescue Exception => e
fail MsRest::DeserializationError.new('Error occurred in deserializing the response', e.message, e.backtrace, result)
end
end
result
end
promise.execute
end
#
# Removes the server's vulnerability assessment.
#
# @param resource_group_name [String] The name of the resource group that
# contains the resource. You can obtain this value from the Azure Resource
# Manager API or the portal.
# @param server_name [String] The name of the server for which the
# vulnerability assessment is defined.
# @param custom_headers [Hash{String => String}] A hash of custom headers that
# will be added to the HTTP request.
#
#
def delete(resource_group_name, server_name, custom_headers:nil)
response = delete_async(resource_group_name, server_name, custom_headers:custom_headers).value!
nil
end
#
# Removes the server's vulnerability assessment.
#
# @param resource_group_name [String] The name of the resource group that
# contains the resource. You can obtain this value from the Azure Resource
# Manager API or the portal.
# @param server_name [String] The name of the server for which the
# vulnerability assessment is defined.
# @param custom_headers [Hash{String => String}] A hash of custom headers that
# will be added to the HTTP request.
#
# @return [MsRestAzure::AzureOperationResponse] HTTP response information.
#
def delete_with_http_info(resource_group_name, server_name, custom_headers:nil)
delete_async(resource_group_name, server_name, custom_headers:custom_headers).value!
end
#
# Removes the server's vulnerability assessment.
#
# @param resource_group_name [String] The name of the resource group that
# contains the resource. You can obtain this value from the Azure Resource
# Manager API or the portal.
# @param server_name [String] The name of the server for which the
# vulnerability assessment is defined.
# @param [Hash{String => String}] A hash of custom headers that will be added
# to the HTTP request.
#
# @return [Concurrent::Promise] Promise object which holds the HTTP response.
#
def delete_async(resource_group_name, server_name, custom_headers:nil)
fail ArgumentError, 'resource_group_name is nil' if resource_group_name.nil?
fail ArgumentError, 'server_name is nil' if server_name.nil?
vulnerability_assessment_name = 'default'
fail ArgumentError, '@client.subscription_id is nil' if @client.subscription_id.nil?
fail ArgumentError, '@client.api_version is nil' if @client.api_version.nil?
request_headers = {}
request_headers['Content-Type'] = 'application/json; charset=utf-8'
# Set Headers
request_headers['x-ms-client-request-id'] = SecureRandom.uuid
request_headers['accept-language'] = @client.accept_language unless @client.accept_language.nil?
path_template = 'subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/servers/{serverName}/vulnerabilityAssessments/{vulnerabilityAssessmentName}'
request_url = @base_url || @client.base_url
options = {
middlewares: [[MsRest::RetryPolicyMiddleware, times: 3, retry: 0.02], [:cookie_jar]],
path_params: {'resourceGroupName' => resource_group_name,'serverName' => server_name,'vulnerabilityAssessmentName' => vulnerability_assessment_name,'subscriptionId' => @client.subscription_id},
query_params: {'api-version' => @client.api_version},
headers: request_headers.merge(custom_headers || {}),
base_url: request_url
}
promise = @client.make_request_async(:delete, path_template, options)
promise = promise.then do |result|
http_response = result.response
status_code = http_response.status
response_content = http_response.body
unless status_code == 200
error_model = JSON.load(response_content)
fail MsRestAzure::AzureOperationError.new(result.request, http_response, error_model)
end
result.request_id = http_response['x-ms-request-id'] unless http_response['x-ms-request-id'].nil?
result
end
promise.execute
end
#
# Lists the vulnerability assessment policies associated with a server.
#
# @param resource_group_name [String] The name of the resource group that
# contains the resource. You can obtain this value from the Azure Resource
# Manager API or the portal.
# @param server_name [String] The name of the server.
# @param custom_headers [Hash{String => String}] A hash of custom headers that
# will be added to the HTTP request.
#
# @return [Array<ServerVulnerabilityAssessment>] operation results.
#
def list_by_server(resource_group_name, server_name, custom_headers:nil)
first_page = list_by_server_as_lazy(resource_group_name, server_name, custom_headers:custom_headers)
first_page.get_all_items
end
#
# Lists the vulnerability assessment policies associated with a server.
#
# @param resource_group_name [String] The name of the resource group that
# contains the resource. You can obtain this value from the Azure Resource
# Manager API or the portal.
# @param server_name [String] The name of the server.
# @param custom_headers [Hash{String => String}] A hash of custom headers that
# will be added to the HTTP request.
#
# @return [MsRestAzure::AzureOperationResponse] HTTP response information.
#
def list_by_server_with_http_info(resource_group_name, server_name, custom_headers:nil)
list_by_server_async(resource_group_name, server_name, custom_headers:custom_headers).value!
end
#
# Lists the vulnerability assessment policies associated with a server.
#
# @param resource_group_name [String] The name of the resource group that
# contains the resource. You can obtain this value from the Azure Resource
# Manager API or the portal.
# @param server_name [String] The name of the server.
# @param [Hash{String => String}] A hash of custom headers that will be added
# to the HTTP request.
#
# @return [Concurrent::Promise] Promise object which holds the HTTP response.
#
def list_by_server_async(resource_group_name, server_name, custom_headers:nil)
fail ArgumentError, 'resource_group_name is nil' if resource_group_name.nil?
fail ArgumentError, 'server_name is nil' if server_name.nil?
fail ArgumentError, '@client.subscription_id is nil' if @client.subscription_id.nil?
fail ArgumentError, '@client.api_version is nil' if @client.api_version.nil?
request_headers = {}
request_headers['Content-Type'] = 'application/json; charset=utf-8'
# Set Headers
request_headers['x-ms-client-request-id'] = SecureRandom.uuid
request_headers['accept-language'] = @client.accept_language unless @client.accept_language.nil?
path_template = 'subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/servers/{serverName}/vulnerabilityAssessments'
request_url = @base_url || @client.base_url
options = {
middlewares: [[MsRest::RetryPolicyMiddleware, times: 3, retry: 0.02], [:cookie_jar]],
path_params: {'resourceGroupName' => resource_group_name,'serverName' => server_name,'subscriptionId' => @client.subscription_id},
query_params: {'api-version' => @client.api_version},
headers: request_headers.merge(custom_headers || {}),
base_url: request_url
}
promise = @client.make_request_async(:get, path_template, options)
promise = promise.then do |result|
http_response = result.response
status_code = http_response.status
response_content = http_response.body
unless status_code == 200
error_model = JSON.load(response_content)
fail MsRestAzure::AzureOperationError.new(result.request, http_response, error_model)
end
result.request_id = http_response['x-ms-request-id'] unless http_response['x-ms-request-id'].nil?
# Deserialize Response
if status_code == 200
begin
parsed_response = response_content.to_s.empty? ? nil : JSON.load(response_content)
result_mapper = Azure::SQL::Mgmt::V2018_06_01_preview::Models::ServerVulnerabilityAssessmentListResult.mapper()
result.body = @client.deserialize(result_mapper, parsed_response)
rescue Exception => e
fail MsRest::DeserializationError.new('Error occurred in deserializing the response', e.message, e.backtrace, result)
end
end
result
end
promise.execute
end
#
# Lists the vulnerability assessment policies associated with a server.
#
# @param next_page_link [String] The NextLink from the previous successful call
# to List operation.
# @param custom_headers [Hash{String => String}] A hash of custom headers that
# will be added to the HTTP request.
#
# @return [ServerVulnerabilityAssessmentListResult] operation results.
#
def list_by_server_next(next_page_link, custom_headers:nil)
response = list_by_server_next_async(next_page_link, custom_headers:custom_headers).value!
response.body unless response.nil?
end
#
# Lists the vulnerability assessment policies associated with a server.
#
# @param next_page_link [String] The NextLink from the previous successful call
# to List operation.
# @param custom_headers [Hash{String => String}] A hash of custom headers that
# will be added to the HTTP request.
#
# @return [MsRestAzure::AzureOperationResponse] HTTP response information.
#
def list_by_server_next_with_http_info(next_page_link, custom_headers:nil)
list_by_server_next_async(next_page_link, custom_headers:custom_headers).value!
end
#
# Lists the vulnerability assessment policies associated with a server.
#
# @param next_page_link [String] The NextLink from the previous successful call
# to List operation.
# @param [Hash{String => String}] A hash of custom headers that will be added
# to the HTTP request.
#
# @return [Concurrent::Promise] Promise object which holds the HTTP response.
#
def list_by_server_next_async(next_page_link, custom_headers:nil)
fail ArgumentError, 'next_page_link is nil' if next_page_link.nil?
request_headers = {}
request_headers['Content-Type'] = 'application/json; charset=utf-8'
# Set Headers
request_headers['x-ms-client-request-id'] = SecureRandom.uuid
request_headers['accept-language'] = @client.accept_language unless @client.accept_language.nil?
path_template = '{nextLink}'
request_url = @base_url || @client.base_url
options = {
middlewares: [[MsRest::RetryPolicyMiddleware, times: 3, retry: 0.02], [:cookie_jar]],
skip_encoding_path_params: {'nextLink' => next_page_link},
headers: request_headers.merge(custom_headers || {}),
base_url: request_url
}
promise = @client.make_request_async(:get, path_template, options)
promise = promise.then do |result|
http_response = result.response
status_code = http_response.status
response_content = http_response.body
unless status_code == 200
error_model = JSON.load(response_content)
fail MsRestAzure::AzureOperationError.new(result.request, http_response, error_model)
end
result.request_id = http_response['x-ms-request-id'] unless http_response['x-ms-request-id'].nil?
# Deserialize Response
if status_code == 200
begin
parsed_response = response_content.to_s.empty? ? nil : JSON.load(response_content)
result_mapper = Azure::SQL::Mgmt::V2018_06_01_preview::Models::ServerVulnerabilityAssessmentListResult.mapper()
result.body = @client.deserialize(result_mapper, parsed_response)
rescue Exception => e
fail MsRest::DeserializationError.new('Error occurred in deserializing the response', e.message, e.backtrace, result)
end
end
result
end
promise.execute
end
#
# Lists the vulnerability assessment policies associated with a server.
#
# @param resource_group_name [String] The name of the resource group that
# contains the resource. You can obtain this value from the Azure Resource
# Manager API or the portal.
# @param server_name [String] The name of the server.
# @param custom_headers [Hash{String => String}] A hash of custom headers that
# will be added to the HTTP request.
#
# @return [ServerVulnerabilityAssessmentListResult] which provide lazy access
# to pages of the response.
#
def list_by_server_as_lazy(resource_group_name, server_name, custom_headers:nil)
response = list_by_server_async(resource_group_name, server_name, custom_headers:custom_headers).value!
unless response.nil?
page = response.body
page.next_method = Proc.new do |next_page_link|
list_by_server_next_async(next_page_link, custom_headers:custom_headers)
end
page
end
end
end
end
| 45.066667 | 203 | 0.7083 |
d53fd106b974d868e579d624f96c8656134b4846 | 598 | Pod::Spec.new do |spec|
spec.name = 'SimplogBase'
spec.version = '0.1.0'
spec.license = { :type => 'MIT' }
spec.homepage = 'https://github.com/nholloh/Simplog'
spec.authors = { 'Niklas Holloh' => 'github@niklasholloh.de' }
spec.summary = 'A simplistic, yet extensible iOS logging framework.'
spec.source = { :git => 'https://github.com/nholloh/Simplog.git', :tag => 'v0.1.0' }
spec.source_files = 'Sources/SimplogBase/**/*.swift'
spec.swift_versions = '5.0', '5.1', '5.2', '5.3', '5.4'
spec.platform = :ios, '9.0'
end
| 46 | 94 | 0.571906 |
e2950c462dc7e99038802f99482a4b5fa4e8540a | 60 | module EasyMailPreview
module ApplicationHelper
end
end
| 12 | 26 | 0.833333 |
ac58b6eb7541ae7dd0644d183276a8f36dbe7aff | 1,176 | class TeamsController < ApplicationController
before_action :authenticate_user!
before_action :authorize!, except: [:new, :create]
def show
if project = @team.projects.first
redirect_to team_project_path(@team, project)
end
end
def new
@team = current_user.teams.build if user_signed_in?
end
def edit
end
def create
@team = current_user.teams.build(team_params)
@team.user_id = current_user.id
if @team.save
@team.authorized!(current_user)
else
render json: format_error_message(@team), status: :unprocessable_entity
end
end
def update
unless @team.update(team_params)
render json: format_error_message(@team), status: :unprocessable_entity
end
end
def destroy
@team.destroy
redirect_to dashboard_path, notice: t("teams.messages.destroy")
end
def settings
end
private
def set_team
@team = Team.find_by(name: params[:name])
routing_error if @team.nil?
end
def authorize!
@team || set_team
forbidden_error unless @team.authorized?(current_user)
end
def team_params
params.require(:team).permit(:name)
end
end | 21 | 77 | 0.687925 |
38566108f3b9216615ce46d2c301f1d4202e9d0e | 1,080 | class Canu < Formula
desc "Single molecule sequence assembler"
homepage "http://canu.readthedocs.org/en/latest/"
url "https://github.com/marbl/canu/archive/v1.3.tar.gz"
sha256 "7a85e4999baf75553f738b9fb263c17772d7630368d3b7321b8d90f3dc584457"
head "https://github.com/marbl/canu.git"
# doi "10.1038/nbt.3238"
# tag "bioinformatics"
bottle do
sha256 "f37d258084205d89ec0aecaa3c04500a394d10b6f357f790ca75bbc40b6f2af3" => :el_capitan
sha256 "564612c7a5b5de07e7dbd46586df47380f0149c78a21c25abcd215a41727bd98" => :yosemite
sha256 "496e8b42bdcca4612cede42d3676345a14bfb234937cfb314d4d65a9cea7ae26" => :mavericks
sha256 "cf424d48cdd5a6a427b77de3dc4ea55fa6a9b299e6c2d0e84baf8e231ee3de94" => :x86_64_linux
end
# Fix fatal error: 'omp.h' file not found
needs :openmp
def install
system "make", "-C", "src"
arch = Pathname.new(Dir["*/bin"][0]).dirname
rm_r arch/"obj"
prefix.install arch
bin.install_symlink prefix/arch/"bin/canu"
doc.install Dir["README.*"]
end
test do
system "#{bin}/canu", "--version"
end
end
| 32.727273 | 94 | 0.743519 |
339ad5e8bc3ba4f6b92910700c564fe5bd570e88 | 775 | class Geoserver < Formula
desc "Java server to share and edit geospatial data"
homepage "http://geoserver.org/"
url "https://downloads.sourceforge.net/project/geoserver/GeoServer/2.13.0/geoserver-2.13.0-bin.zip"
sha256 "0248645869d042f835da0c69b0554ae9379623ecaf7970cab2782cbfa03f6b76"
bottle :unneeded
def install
libexec.install Dir["*"]
(bin/"geoserver").write <<~EOS
#!/bin/sh
if [ -z "$1" ]; then
echo "Usage: $ geoserver path/to/data/dir"
else
cd "#{libexec}" && java -DGEOSERVER_DATA_DIR=$1 -jar start.jar
fi
EOS
end
def caveats; <<~EOS
To start geoserver:
geoserver path/to/data/dir
EOS
end
test do
assert_match "geoserver path", shell_output("#{bin}/geoserver")
end
end
| 25 | 101 | 0.664516 |
ffafa94612d02a4adb441439e869304aafb206ff | 1,083 | require 'json'
package = JSON.parse(File.read(File.join(__dir__, 'package.json')))
Pod::Spec.new do |s|
s.name = 'CodePush'
s.version = package['version'].gsub(/v|-beta/, '')
s.summary = package['description']
s.author = package['author']
s.license = package['license']
s.homepage = package['homepage']
s.source = { :git => 'https://github.com/microsoft/react-native-code-push.git', :tag => "v#{s.version}"}
s.ios.deployment_target = '7.0'
s.tvos.deployment_target = '9.0'
s.preserve_paths = '*.js'
s.library = 'z'
s.source_files = 'ios/CodePush/*.{h,m}'
s.public_header_files = ['ios/CodePush/CodePush.h']
# Note: Even though there are copy/pasted versions of some of these dependencies in the repo,
# we explicitly let CocoaPods pull in the versions below so all dependencies are resolved and
# linked properly at a parent workspace level.
s.dependency 'React'
s.dependency 'SSZipArchive', '~> 2.2.2'
s.dependency 'JWT', '~> 3.0.0-beta.12'
s.dependency 'Base64', '~> 1.1'
end
| 38.678571 | 114 | 0.638042 |
4ad4dd6990d41dfbc441a25c03a2fd25a1d9b96f | 2,294 | # The MIT License (MIT)
# Copyright (c) 2018 Mike DeAngelo Looker Data Sciences, Inc.
# Permission is hereby granted, free of charge, to any person obtaining a copy of
# this software and associated documentation files (the "Software"), to deal in
# the Software without restriction, including without limitation the rights to
# use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
# the Software, and to permit persons to whom the Software is furnished to do so,
# subject to the following conditions:
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
# FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
# COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
# IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
require 'gzr/commands/group/member_users'
RSpec.describe Gzr::Commands::Group::MemberUsers do
it "executes `member_users` command successfully" do
require 'sawyer'
mock_response_doc = { :id=>1, :last_name=>"foo", :first_name=>"bar", :email=>"fbar@my.company.com" }
mock_response = double(Sawyer::Resource, mock_response_doc)
allow(mock_response).to receive(:to_attrs).and_return(mock_response_doc)
mock_sdk = Object.new
mock_sdk.define_singleton_method(:logout) { }
mock_sdk.define_singleton_method(:all_group_users) do |group_id,body|
return body[:page] == 1 ? [mock_response] : []
end
output = StringIO.new
options = { :fields=>'id,last_name,first_name,email' }
command = Gzr::Commands::Group::MemberUsers.new(1,options)
command.instance_variable_set(:@sdk, mock_sdk)
command.execute(output: output)
expect(output.string).to eq <<-OUT
+--+---------+----------+-------------------+
|id|last_name|first_name|email |
+--+---------+----------+-------------------+
| 1|foo |bar |fbar@my.company.com|
+--+---------+----------+-------------------+
OUT
end
end
| 43.283019 | 104 | 0.694856 |
0178ab9d006e96088673e90b170bb76951fbdc99 | 746 | $LOAD_PATH.unshift File.expand_path("../../lib", __FILE__)
require 'active_record'
ActiveRecord::Base.establish_connection adapter: 'sqlite3', database: ':memory:'
#ActiveRecord::Base.logger = Logger.new(STDOUT)
load File.dirname(__FILE__) + '/schema.rb'
require 'dynamic_record'
require 'database_cleaner'
require 'rspec-sqlimit'
I18n.available_locales = [:en, :fr]
Globalize.fallbacks = {:en => [:en, :fr], :fr => [:fr, :en]}
RSpec.configure do |config|
config.color = true
config.formatter = :documentation
config.before(:suite) do
DatabaseCleaner.strategy = :transaction
DatabaseCleaner.clean_with(:truncation)
end
config.around(:each) do |example|
DatabaseCleaner.cleaning do
example.run
end
end
end
| 24.064516 | 80 | 0.719839 |
e24166297180c5099289149c254b64191f3f1531 | 211 | class CreateTestResources < ActiveRecord::Migration[5.1]
def change
create_table :test_resources do |t|
t.string :name
t.integer :age
t.string :kind
t.timestamps
end
end
end
| 17.583333 | 56 | 0.654028 |
382962f92d1ab3f1d9de31a2522de11afdd2b23d | 551 | # frozen_string_literal: true
module Ez
module Status
class ApplicationCell < Cell::ViewModel
self.view_paths = ["#{Ez::Status::Engine.root}/app/cells"]
CSS_SCOPE = 'ez-status'
def div_for(item, &block)
content_tag :div, class: css_for(item), &block
end
def css_for(item)
scoped_item = "#{CSS_SCOPE}-#{item}"
custom_css_map[scoped_item] || scoped_item
end
def custom_css_map
@custom_css_map ||= Ez::Status.config.ui_custom_css_map || {}
end
end
end
end
| 21.192308 | 69 | 0.622505 |
1a440e3ebd080af0f19fc98644d54004b2ae2bad | 735 | Pod::Spec.new do |s|
s.name = "PagerTabStripView"
s.version = "3.1.1"
s.summary = "PagerTabStripView allows navigating through pages using a custom navigation bar in SwiftUI."
s.homepage = "https://github.com/xmartlabs/PagerTabStripView"
s.license = { type: 'MIT', file: 'LICENSE' }
s.authors = { "Xmartlabs SRL" => "swift@xmartlabs.com" }
s.source = { git: "https://github.com/xmartlabs/PagerTabStripView.git", tag: s.version.to_s }
s.social_media_url = 'https://twitter.com/xmartlabs'
s.ios.deployment_target = '14.0'
s.swift_version = '5.0'
s.requires_arc = true
s.ios.source_files = 'Sources/**/*.{swift}'
s.ios.frameworks = 'SwiftUI'
end
| 45.9375 | 116 | 0.629932 |
f7375bc59824eb33d71b49d85a2d0c9ba1d7bd18 | 150 | class AddTokenTypeToUserTokens < ActiveRecord::Migration[5.0]
def change
add_column :user_tokens, :token_type, :string, default: :web
end
end
| 25 | 64 | 0.76 |
e89963cab18439986f1517d0746ffa0174a26a32 | 99 | class Library < ApplicationRecord
belongs_to :user
has_one :podcast
has_one :music
end
| 16.5 | 33 | 0.727273 |
268aae80767eaad555cbe4cb2c150222af7516f5 | 1,455 | class Libplctag < Formula
desc "Portable and simple API for accessing AB PLC data over Ethernet"
homepage "https://github.com/libplctag/libplctag"
url "https://github.com/libplctag/libplctag/archive/v2.2.1.tar.gz"
sha256 "7fa17a9bc82548daea5bc14e6d0e2aac45e684d96f866aa83bdfa7e0285174f6"
license any_of: ["LGPL-2.0-or-later", "MPL-2.0"]
livecheck do
url :stable
strategy :github_latest
end
bottle do
sha256 cellar: :any, arm64_big_sur: "4056e0e3bb70d7ae73466b3cd4ebfa1263686488c02093d9971b3167fdc0fb2f"
sha256 cellar: :any, big_sur: "5b0524a3cbd9bb18363e1542575bb15d606d76af01c1951af31a1487281f9bb7"
sha256 cellar: :any, catalina: "5b4e7eb99c7e819414830fa910e6bdac55bf99bf5c9cb185e6d47ab058f8dfbb"
sha256 cellar: :any, mojave: "3a6adae63e7af57d0908e8a22420afb5dfb4288acc9806fa6d6d1573b64c25e3"
end
depends_on "cmake" => :build
def install
system "cmake", ".", *std_cmake_args
system "make", "install"
end
test do
(testpath/"test.c").write <<~EOS
#include <stdlib.h>
#include <libplctag.h>
int main(int argc, char **argv) {
int32_t tag = plc_tag_create("protocol=ab_eip&gateway=192.168.1.42&path=1,0&cpu=LGX&elem_size=4&elem_count=10&name=myDINTArray", 1);
if (!tag) abort();
plc_tag_destroy(tag);
return 0;
}
EOS
system ENV.cc, "test.c", "-L#{lib}", "-lplctag", "-o", "test"
system "./test"
end
end
| 33.837209 | 140 | 0.701031 |
1144c4f1a201a29475c73b893cd073b5a6fe5f04 | 213 | class SongsWorker
include Sidekiq::Worker
require 'csv'
def perform(songs_file)
CSV.foreach(song_file, headers: true) do |song|
Song.create(title: song[0], artist_name: song[1])
end
end
end | 19.363636 | 55 | 0.690141 |
260ba5d01399fe321d98541a4862735be194f2c1 | 704 | # frozen_string_literal: true
module Esse
class IndexMapping
FILENAMES = %w[mapping mappings].freeze
def initialize(body: {}, paths: [], filenames: FILENAMES)
@paths = Array(paths)
@filenames = Array(filenames)
@mappings = body
end
# This method will be overwrited when passing a block during the
# mapping defination
def to_h
return @mappings unless @mappings.empty?
from_template || @mappings
end
def body
to_h
end
def empty?
body.empty?
end
protected
def from_template
return if @paths.empty?
loader = Esse::TemplateLoader.new(@paths)
loader.read(*@filenames)
end
end
end
| 18.051282 | 68 | 0.633523 |
263aa4fcf6d6b969de191bd1d3b2c4d939e7b3a1 | 2,383 | #-- encoding: UTF-8
#-- copyright
# OpenProject is an open source project management software.
# Copyright (C) 2012-2021 the OpenProject GmbH
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License version 3.
#
# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
# Copyright (C) 2006-2013 Jean-Philippe Lang
# Copyright (C) 2010-2013 the ChiliProject Team
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# See docs/COPYRIGHT.rdoc for more details.
#++
module Cron
class CronJob < ApplicationJob
class_attribute :cron_expression
# List of registered jobs, requires eager load in dev(!)
class_attribute :registered_jobs, default: []
class << self
##
# Register new job class(es)
def register!(*job_classes)
Array(job_classes).each do |clz|
raise ArgumentError, "Needs to be subclass of ::Cron::CronJob" unless clz.ancestors.include?(self)
registered_jobs << clz
end
end
##
# Ensure the job is scheduled unless it is already
def ensure_scheduled!
# Ensure scheduled only onced
return if scheduled?
Rails.logger.info { "Scheduling #{name} recurrent background job." }
set(cron: cron_expression).perform_later
end
##
# Remove the scheduled job, if any
def remove
delayed_job&.destroy
end
##
# Is there a job scheduled?
def scheduled?
delayed_job.present?
end
def delayed_job
Delayed::Job
.where('handler LIKE ?', "%job_class: #{name}%")
.first
end
end
end
end
| 30.164557 | 108 | 0.681914 |
1a0db8eaa593087278f01f31c0265e7714ff730f | 17,216 | # HTTPClient - HTTP client library.
# Copyright (C) 2000-2015 NAKAMURA, Hiroshi <nahi@ruby-lang.org>.
#
# This program is copyrighted free software by NAKAMURA, Hiroshi. You can
# redistribute it and/or modify it under the same terms of Ruby's license;
# either the dual license version in 2003, or any later version.
require 'java'
require 'httpclient/ssl_config'
class HTTPClient
unless defined?(SSLSocket)
class JavaSocketWrap
java_import 'java.net.InetSocketAddress'
java_import 'java.io.BufferedInputStream'
BUF_SIZE = 1024 * 16
def self.normalize_timeout(timeout)
[Java::JavaLang::Integer::MAX_VALUE, timeout].min
end
def self.connect(socket, site, opts = {})
socket_addr = InetSocketAddress.new(site.host, site.port)
if opts[:connect_timeout]
socket.connect(socket_addr, normalize_timeout(opts[:connect_timeout]))
else
socket.connect(socket_addr)
end
socket.setSoTimeout(normalize_timeout(opts[:so_timeout])) if opts[:so_timeout]
socket.setKeepAlive(true) if opts[:tcp_keepalive]
socket
end
def initialize(socket, debug_dev = nil)
@socket = socket
@debug_dev = debug_dev
@outstr = @socket.getOutputStream
@instr = BufferedInputStream.new(@socket.getInputStream)
@buf = (' ' * BUF_SIZE).to_java_bytes
@bufstr = ''
end
def close
@socket.close
end
def closed?
@socket.isClosed
end
def eof?
@socket.isClosed
end
def gets(rs)
while (size = @bufstr.index(rs)).nil?
if fill() == -1
size = @bufstr.size
break
end
end
str = @bufstr.slice!(0, size + rs.size)
debug(str)
str
end
def read(size, buf = nil)
while @bufstr.size < size
if fill() == -1
break
end
end
str = @bufstr.slice!(0, size)
debug(str)
if buf
buf.replace(str)
else
str
end
end
def readpartial(size, buf = nil)
while @bufstr.size == 0
if fill() == -1
raise EOFError.new('end of file reached')
end
end
str = @bufstr.slice!(0, size)
debug(str)
if buf
buf.replace(str)
else
str
end
end
def <<(str)
rv = @outstr.write(str.to_java_bytes)
debug(str)
rv
end
def flush
@socket.flush
end
def sync
true
end
def sync=(sync)
unless sync
raise "sync = false is not supported. This option was introduced for backward compatibility just in case."
end
end
private
def fill
begin
size = @instr.read(@buf)
if size > 0
@bufstr << String.from_java_bytes(@buf, Encoding::BINARY)[0, size]
end
size
rescue java.io.IOException => e
raise OpenSSL::SSL::SSLError.new("#{e.class}: #{e.getMessage}")
end
end
def debug(str)
@debug_dev << str if @debug_dev && str
end
end
class JRubySSLSocket < JavaSocketWrap
java_import 'java.io.ByteArrayInputStream'
java_import 'java.io.InputStreamReader'
java_import 'java.net.Socket'
java_import 'java.security.KeyStore'
java_import 'java.security.cert.Certificate'
java_import 'java.security.cert.CertificateFactory'
java_import 'javax.net.ssl.KeyManagerFactory'
java_import 'javax.net.ssl.SSLContext'
java_import 'javax.net.ssl.SSLSocketFactory'
java_import 'javax.net.ssl.TrustManager'
java_import 'javax.net.ssl.TrustManagerFactory'
java_import 'javax.net.ssl.X509TrustManager'
java_import 'org.jruby.ext.openssl.x509store.PEMInputOutput'
class JavaCertificate
attr_reader :cert
def initialize(cert)
@cert = cert
end
def subject
@cert.getSubjectDN
end
def to_text
@cert.toString
end
def to_pem
'(not in PEM format)'
end
end
class SSLStoreContext
attr_reader :current_cert, :chain, :error_depth, :error, :error_string
def initialize(current_cert, chain, error_depth, error, error_string)
@current_cert, @chain, @error_depth, @error, @error_string =
current_cert, chain, error_depth, error, error_string
end
end
class JSSEVerifyCallback
def initialize(verify_callback)
@verify_callback = verify_callback
end
def call(is_ok, chain, error_depth = -1, error = -1, error_string = '(unknown)')
if @verify_callback
ruby_chain = chain.map { |cert|
JavaCertificate.new(cert)
}.reverse
# NOTE: The order depends on provider implementation
ruby_chain.each do |cert|
is_ok = @verify_callback.call(
is_ok,
SSLStoreContext.new(cert, ruby_chain, error_depth, error, error_string)
)
end
end
is_ok
end
end
class VerifyNoneTrustManagerFactory
class VerifyNoneTrustManager
include X509TrustManager
def initialize(verify_callback)
@verify_callback = JSSEVerifyCallback.new(verify_callback)
end
def checkServerTrusted(chain, authType)
@verify_callback.call(true, chain)
end
def checkClientTrusted(chain, authType); end
def getAcceptedIssuers; end
end
def initialize(verify_callback = nil)
@verify_callback = verify_callback
end
def init(trustStore)
@managers = [VerifyNoneTrustManager.new(@verify_callback)].to_java(X509TrustManager)
end
def getTrustManagers
@managers
end
end
class SystemTrustManagerFactory
class SystemTrustManager
include X509TrustManager
def initialize(original, verify_callback)
@original = original
@verify_callback = JSSEVerifyCallback.new(verify_callback)
end
def checkServerTrusted(chain, authType)
is_ok = false
excn = nil
# TODO can we detect the depth from excn?
error_depth = -1
error = nil
error_message = nil
begin
@original.checkServerTrusted(chain, authType)
is_ok = true
rescue java.security.cert.CertificateException => excn
is_ok = false
error = excn.class.name
error_message = excn.getMessage
end
is_ok = @verify_callback.call(is_ok, chain, error_depth, error, error_message)
unless is_ok
excn ||= OpenSSL::SSL::SSLError.new('verifycallback failed')
raise excn
end
end
def checkClientTrusted(chain, authType); end
def getAcceptedIssuers; end
end
def initialize(verify_callback = nil)
@verify_callback = verify_callback
end
def init(trust_store)
tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm)
tmf.java_method(:init, [KeyStore]).call(trust_store)
@original = tmf.getTrustManagers.find { |tm|
tm.is_a?(X509TrustManager)
}
@managers = [SystemTrustManager.new(@original, @verify_callback)].to_java(X509TrustManager)
end
def getTrustManagers
@managers
end
end
module PEMUtils
def self.read_certificate(pem)
cert = pem.sub(/.*?-----BEGIN CERTIFICATE-----/m, '').sub(/-----END CERTIFICATE-----.*?/m, '')
der = cert.unpack('m*').first
cf = CertificateFactory.getInstance('X.509')
cf.generateCertificate(ByteArrayInputStream.new(der.to_java_bytes))
end
def self.read_private_key(pem, password)
if password
password = password.unpack('C*').to_java(:char)
end
PEMInputOutput.read_private_key(InputStreamReader.new(ByteArrayInputStream.new(pem.to_java_bytes)), password)
end
end
class KeyStoreLoader
PASSWORD = 16.times.map { rand(256) }.to_java(:char)
def initialize
@keystore = KeyStore.getInstance('JKS')
@keystore.load(nil)
end
def add(cert_source, key_source, password)
cert_str = cert_source.respond_to?(:to_pem) ? cert_source.to_pem : File.read(cert_source.to_s)
cert = PEMUtils.read_certificate(cert_str)
@keystore.setCertificateEntry('client_cert', cert)
key_str = key_source.respond_to?(:to_pem) ? key_source.to_pem : File.read(key_source.to_s)
key_pair = PEMUtils.read_private_key(key_str, password)
@keystore.setKeyEntry('client_key', key_pair.getPrivate, PASSWORD, [cert].to_java(Certificate))
end
def keystore
@keystore
end
end
class TrustStoreLoader
attr_reader :size
def initialize
@trust_store = KeyStore.getInstance('JKS')
@trust_store.load(nil)
@size = 0
end
def add(cert_source)
return if cert_source == :default
if cert_source.respond_to?(:to_pem)
pem = cert_source.to_pem
load_pem(pem)
elsif File.directory?(cert_source)
warn("#{cert_source}: directory not yet supported")
return
else
pem = nil
File.read(cert_source).each_line do |line|
case line
when /-----BEGIN CERTIFICATE-----/
pem = ''
when /-----END CERTIFICATE-----/
load_pem(pem)
# keep parsing in case where multiple certificates in a file
else
if pem
pem << line
end
end
end
end
end
def trust_store
if @size == 0
nil
else
@trust_store
end
end
private
def load_pem(pem)
cert = PEMUtils.read_certificate(pem)
@size += 1
@trust_store.setCertificateEntry("cert_#{@size}", cert)
end
end
# Ported from commons-httpclient 'BrowserCompatHostnameVerifier'
class BrowserCompatHostnameVerifier
BAD_COUNTRY_2LDS = %w(ac co com ed edu go gouv gov info lg ne net or org).sort
require 'ipaddr'
def extract_sans(cert, subject_type)
sans = cert.getSubjectAlternativeNames rescue nil
if sans.nil?
return nil
end
sans.find_all { |san|
san.first.to_i == subject_type
}.map { |san|
san[1]
}
end
def extract_cn(cert)
subject = cert.getSubjectX500Principal()
if subject
subject_dn = javax.naming.ldap.LdapName.new(subject.toString)
subject_dn.getRdns.to_a.reverse.each do |rdn|
attributes = rdn.toAttributes
cn = attributes.get('cn')
if cn
if value = cn.get
return value.to_s
end
end
end
end
end
def ipaddr?(addr)
!(IPAddr.new(addr) rescue nil).nil?
end
def verify(hostname, cert)
is_ipaddr = ipaddr?(hostname)
sans = extract_sans(cert, is_ipaddr ? 7 : 2)
cn = extract_cn(cert)
if sans
sans.each do |san|
return true if match_identify(hostname, san)
end
raise OpenSSL::SSL::SSLError.new("Certificate for <#{hostname}> doesn't match any of the subject alternative names: #{sans}")
elsif cn
return true if match_identify(hostname, cn)
raise OpenSSL::SSL::SSLError.new("Certificate for <#{hostname}> doesn't match common name of the certificate subject: #{cn}")
end
raise OpenSSL::SSL::SSLError.new("Certificate subject for for <#{hostname}> doesn't contain a common name and does not have alternative names")
end
def match_identify(hostname, identity)
if hostname.nil?
return false
end
hostname = hostname.downcase
identity = identity.downcase
parts = identity.split('.')
if parts.length >= 3 && parts.first.end_with?('*') && valid_country_wildcard(parts)
create_wildcard_regexp(identity) =~ hostname
else
hostname == identity
end
end
def create_wildcard_regexp(value)
# Escape first then search '\*' for meta-char interpolation
labels = value.split('.').map { |e| Regexp.escape(e) }
# Handle '*'s only at the left-most label, exclude A-label and U-label
labels[0].gsub!(/\\\*/, '[^.]+') if !labels[0].start_with?('xn\-\-') and labels[0].ascii_only?
/\A#{labels.join('\.')}\z/i
end
def valid_country_wildcard(parts)
if parts.length != 3 || parts[2].length != 2
true
else
!BAD_COUNTRY_2LDS.include?(parts[1])
end
end
end
def self.create_socket(session)
opts = {
:connect_timeout => session.connect_timeout * 1000,
# send_timeout is ignored in JRuby
:so_timeout => session.receive_timeout * 1000,
:tcp_keepalive => session.tcp_keepalive,
:debug_dev => session.debug_dev
}
socket = nil
begin
if session.proxy
site = session.proxy || session.dest
socket = JavaSocketWrap.connect(Socket.new, site, opts)
session.connect_ssl_proxy(JavaSocketWrap.new(socket), Util.urify(session.dest.to_s))
end
new(socket, session.dest, session.ssl_config, opts)
rescue
socket.close if socket
raise
end
end
DEFAULT_SSL_PROTOCOL = (java.lang.System.getProperty('java.specification.version') == '1.7') ? 'TLSv1.2' : 'TLS'
def initialize(socket, dest, config, opts = {})
@config = config
begin
@ssl_socket = create_ssl_socket(socket, dest, config, opts)
ssl_version = java_ssl_version(config)
@ssl_socket.setEnabledProtocols([ssl_version].to_java(java.lang.String)) if ssl_version != DEFAULT_SSL_PROTOCOL
if config.ciphers != SSLConfig::CIPHERS_DEFAULT
@ssl_socket.setEnabledCipherSuites(config.ciphers.to_java(java.lang.String))
end
ssl_connect(dest.host)
rescue java.security.GeneralSecurityException => e
raise OpenSSL::SSL::SSLError.new(e.getMessage)
rescue java.net.SocketTimeoutException => e
raise HTTPClient::ConnectTimeoutError.new(e.getMessage)
rescue java.io.IOException => e
raise OpenSSL::SSL::SSLError.new("#{e.class}: #{e.getMessage}")
end
super(@ssl_socket, opts[:debug_dev])
end
def java_ssl_version(config)
if config.ssl_version == :auto
DEFAULT_SSL_PROTOCOL
else
config.ssl_version.to_s.tr('_', '.')
end
end
def create_ssl_context(config)
unless config.cert_store_crl_items.empty?
raise NotImplementedError.new('Manual CRL configuration is not yet supported')
end
km = nil
if config.client_cert && config.client_key
loader = KeyStoreLoader.new
loader.add(config.client_cert, config.client_key, config.client_key_pass)
kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm)
kmf.init(loader.keystore, KeyStoreLoader::PASSWORD)
km = kmf.getKeyManagers
end
trust_store = nil
verify_callback = config.verify_callback || config.method(:default_verify_callback)
if !config.verify?
tmf = VerifyNoneTrustManagerFactory.new(verify_callback)
else
tmf = SystemTrustManagerFactory.new(verify_callback)
loader = TrustStoreLoader.new
config.cert_store_items.each do |item|
loader.add(item)
end
trust_store = loader.trust_store
end
tmf.init(trust_store)
tm = tmf.getTrustManagers
ctx = SSLContext.getInstance(java_ssl_version(config))
ctx.init(km, tm, nil)
if config.timeout
ctx.getClientSessionContext.setSessionTimeout(config.timeout)
end
ctx
end
def create_ssl_socket(socket, dest, config, opts)
ctx = create_ssl_context(config)
factory = ctx.getSocketFactory
unless socket
# Create a plain socket first to set connection timeouts on,
# then wrap it in a SSL socket so that SNI gets setup on it.
socket = javax.net.SocketFactory.getDefault.createSocket
JavaSocketWrap.connect(socket, dest, opts)
end
factory.createSocket(socket, dest.host, dest.port, true)
end
def peer_cert
@peer_cert
end
private
def ssl_connect(hostname)
@ssl_socket.startHandshake
ssl_session = @ssl_socket.getSession
@peer_cert = JavaCertificate.new(ssl_session.getPeerCertificates.first)
if $DEBUG
warn("Protocol version: #{ssl_session.getProtocol}")
warn("Cipher: #{@ssl_socket.getSession.getCipherSuite}")
end
post_connection_check(hostname)
end
def post_connection_check(hostname)
if !@config.verify?
return
else
BrowserCompatHostnameVerifier.new.verify(hostname, @peer_cert.cert)
end
end
end
SSLSocket = JRubySSLSocket
end
end
| 28.934454 | 151 | 0.619308 |
3960f5744e76e70c27d0a2267f77fc1422ef87f5 | 30,040 | # 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
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
require 'date'
require 'google/apis/core/base_service'
require 'google/apis/core/json_representation'
require 'google/apis/core/hashable'
require 'google/apis/errors'
module Google
module Apis
module ManagedidentitiesV1alpha1
class AttachTrustRequest
class Representation < Google::Apis::Core::JsonRepresentation; end
include Google::Apis::Core::JsonObjectSupport
end
class Binding
class Representation < Google::Apis::Core::JsonRepresentation; end
include Google::Apis::Core::JsonObjectSupport
end
class CancelOperationRequest
class Representation < Google::Apis::Core::JsonRepresentation; end
include Google::Apis::Core::JsonObjectSupport
end
class DailyCycle
class Representation < Google::Apis::Core::JsonRepresentation; end
include Google::Apis::Core::JsonObjectSupport
end
class Date
class Representation < Google::Apis::Core::JsonRepresentation; end
include Google::Apis::Core::JsonObjectSupport
end
class DenyMaintenancePeriod
class Representation < Google::Apis::Core::JsonRepresentation; end
include Google::Apis::Core::JsonObjectSupport
end
class DetachTrustRequest
class Representation < Google::Apis::Core::JsonRepresentation; end
include Google::Apis::Core::JsonObjectSupport
end
class Domain
class Representation < Google::Apis::Core::JsonRepresentation; end
include Google::Apis::Core::JsonObjectSupport
end
class Empty
class Representation < Google::Apis::Core::JsonRepresentation; end
include Google::Apis::Core::JsonObjectSupport
end
class Expr
class Representation < Google::Apis::Core::JsonRepresentation; end
include Google::Apis::Core::JsonObjectSupport
end
class GoogleCloudManagedidentitiesV1OpMetadata
class Representation < Google::Apis::Core::JsonRepresentation; end
include Google::Apis::Core::JsonObjectSupport
end
class GoogleCloudManagedidentitiesV1alpha1OpMetadata
class Representation < Google::Apis::Core::JsonRepresentation; end
include Google::Apis::Core::JsonObjectSupport
end
class GoogleCloudManagedidentitiesV1beta1OpMetadata
class Representation < Google::Apis::Core::JsonRepresentation; end
include Google::Apis::Core::JsonObjectSupport
end
class GoogleCloudSaasacceleratorManagementProvidersV1Instance
class Representation < Google::Apis::Core::JsonRepresentation; end
include Google::Apis::Core::JsonObjectSupport
end
class GoogleCloudSaasacceleratorManagementProvidersV1MaintenanceSchedule
class Representation < Google::Apis::Core::JsonRepresentation; end
include Google::Apis::Core::JsonObjectSupport
end
class GoogleCloudSaasacceleratorManagementProvidersV1MaintenanceSettings
class Representation < Google::Apis::Core::JsonRepresentation; end
include Google::Apis::Core::JsonObjectSupport
end
class GoogleCloudSaasacceleratorManagementProvidersV1NodeSloMetadata
class Representation < Google::Apis::Core::JsonRepresentation; end
include Google::Apis::Core::JsonObjectSupport
end
class GoogleCloudSaasacceleratorManagementProvidersV1ProvisionedResource
class Representation < Google::Apis::Core::JsonRepresentation; end
include Google::Apis::Core::JsonObjectSupport
end
class GoogleCloudSaasacceleratorManagementProvidersV1SloEligibility
class Representation < Google::Apis::Core::JsonRepresentation; end
include Google::Apis::Core::JsonObjectSupport
end
class GoogleCloudSaasacceleratorManagementProvidersV1SloExclusion
class Representation < Google::Apis::Core::JsonRepresentation; end
include Google::Apis::Core::JsonObjectSupport
end
class GoogleCloudSaasacceleratorManagementProvidersV1SloMetadata
class Representation < Google::Apis::Core::JsonRepresentation; end
include Google::Apis::Core::JsonObjectSupport
end
class ListDomainsResponse
class Representation < Google::Apis::Core::JsonRepresentation; end
include Google::Apis::Core::JsonObjectSupport
end
class ListLocationsResponse
class Representation < Google::Apis::Core::JsonRepresentation; end
include Google::Apis::Core::JsonObjectSupport
end
class ListOperationsResponse
class Representation < Google::Apis::Core::JsonRepresentation; end
include Google::Apis::Core::JsonObjectSupport
end
class ListSqlIntegrationsResponse
class Representation < Google::Apis::Core::JsonRepresentation; end
include Google::Apis::Core::JsonObjectSupport
end
class Location
class Representation < Google::Apis::Core::JsonRepresentation; end
include Google::Apis::Core::JsonObjectSupport
end
class MaintenancePolicy
class Representation < Google::Apis::Core::JsonRepresentation; end
include Google::Apis::Core::JsonObjectSupport
end
class MaintenanceWindow
class Representation < Google::Apis::Core::JsonRepresentation; end
include Google::Apis::Core::JsonObjectSupport
end
class Operation
class Representation < Google::Apis::Core::JsonRepresentation; end
include Google::Apis::Core::JsonObjectSupport
end
class OperationMetadata
class Representation < Google::Apis::Core::JsonRepresentation; end
include Google::Apis::Core::JsonObjectSupport
end
class Policy
class Representation < Google::Apis::Core::JsonRepresentation; end
include Google::Apis::Core::JsonObjectSupport
end
class ReconfigureTrustRequest
class Representation < Google::Apis::Core::JsonRepresentation; end
include Google::Apis::Core::JsonObjectSupport
end
class ResetAdminPasswordRequest
class Representation < Google::Apis::Core::JsonRepresentation; end
include Google::Apis::Core::JsonObjectSupport
end
class ResetAdminPasswordResponse
class Representation < Google::Apis::Core::JsonRepresentation; end
include Google::Apis::Core::JsonObjectSupport
end
class SqlIntegration
class Representation < Google::Apis::Core::JsonRepresentation; end
include Google::Apis::Core::JsonObjectSupport
end
class Schedule
class Representation < Google::Apis::Core::JsonRepresentation; end
include Google::Apis::Core::JsonObjectSupport
end
class SetIamPolicyRequest
class Representation < Google::Apis::Core::JsonRepresentation; end
include Google::Apis::Core::JsonObjectSupport
end
class Status
class Representation < Google::Apis::Core::JsonRepresentation; end
include Google::Apis::Core::JsonObjectSupport
end
class TestIamPermissionsRequest
class Representation < Google::Apis::Core::JsonRepresentation; end
include Google::Apis::Core::JsonObjectSupport
end
class TestIamPermissionsResponse
class Representation < Google::Apis::Core::JsonRepresentation; end
include Google::Apis::Core::JsonObjectSupport
end
class TimeOfDay
class Representation < Google::Apis::Core::JsonRepresentation; end
include Google::Apis::Core::JsonObjectSupport
end
class TrustProp
class Representation < Google::Apis::Core::JsonRepresentation; end
include Google::Apis::Core::JsonObjectSupport
end
class UpdatePolicy
class Representation < Google::Apis::Core::JsonRepresentation; end
include Google::Apis::Core::JsonObjectSupport
end
class ValidateTrustRequest
class Representation < Google::Apis::Core::JsonRepresentation; end
include Google::Apis::Core::JsonObjectSupport
end
class WeeklyCycle
class Representation < Google::Apis::Core::JsonRepresentation; end
include Google::Apis::Core::JsonObjectSupport
end
class AttachTrustRequest
# @private
class Representation < Google::Apis::Core::JsonRepresentation
property :trust_prop, as: 'trust', class: Google::Apis::ManagedidentitiesV1alpha1::TrustProp, decorator: Google::Apis::ManagedidentitiesV1alpha1::TrustProp::Representation
end
end
class Binding
# @private
class Representation < Google::Apis::Core::JsonRepresentation
property :condition, as: 'condition', class: Google::Apis::ManagedidentitiesV1alpha1::Expr, decorator: Google::Apis::ManagedidentitiesV1alpha1::Expr::Representation
collection :members, as: 'members'
property :role, as: 'role'
end
end
class CancelOperationRequest
# @private
class Representation < Google::Apis::Core::JsonRepresentation
end
end
class DailyCycle
# @private
class Representation < Google::Apis::Core::JsonRepresentation
property :duration, as: 'duration'
property :start_time, as: 'startTime', class: Google::Apis::ManagedidentitiesV1alpha1::TimeOfDay, decorator: Google::Apis::ManagedidentitiesV1alpha1::TimeOfDay::Representation
end
end
class Date
# @private
class Representation < Google::Apis::Core::JsonRepresentation
property :day, as: 'day'
property :month, as: 'month'
property :year, as: 'year'
end
end
class DenyMaintenancePeriod
# @private
class Representation < Google::Apis::Core::JsonRepresentation
property :end_date, as: 'endDate', class: Google::Apis::ManagedidentitiesV1alpha1::Date, decorator: Google::Apis::ManagedidentitiesV1alpha1::Date::Representation
property :start_date, as: 'startDate', class: Google::Apis::ManagedidentitiesV1alpha1::Date, decorator: Google::Apis::ManagedidentitiesV1alpha1::Date::Representation
property :time, as: 'time', class: Google::Apis::ManagedidentitiesV1alpha1::TimeOfDay, decorator: Google::Apis::ManagedidentitiesV1alpha1::TimeOfDay::Representation
end
end
class DetachTrustRequest
# @private
class Representation < Google::Apis::Core::JsonRepresentation
property :trust_prop, as: 'trust', class: Google::Apis::ManagedidentitiesV1alpha1::TrustProp, decorator: Google::Apis::ManagedidentitiesV1alpha1::TrustProp::Representation
end
end
class Domain
# @private
class Representation < Google::Apis::Core::JsonRepresentation
property :audit_logs_enabled, as: 'auditLogsEnabled'
collection :authorized_networks, as: 'authorizedNetworks'
property :create_time, as: 'createTime'
property :fqdn, as: 'fqdn'
hash :labels, as: 'labels'
collection :locations, as: 'locations'
property :managed_identities_admin_name, as: 'managedIdentitiesAdminName'
property :name, as: 'name'
property :reserved_ip_range, as: 'reservedIpRange'
property :state, as: 'state'
property :status_message, as: 'statusMessage'
collection :trusts, as: 'trusts', class: Google::Apis::ManagedidentitiesV1alpha1::TrustProp, decorator: Google::Apis::ManagedidentitiesV1alpha1::TrustProp::Representation
property :update_time, as: 'updateTime'
end
end
class Empty
# @private
class Representation < Google::Apis::Core::JsonRepresentation
end
end
class Expr
# @private
class Representation < Google::Apis::Core::JsonRepresentation
property :description, as: 'description'
property :expression, as: 'expression'
property :location, as: 'location'
property :title, as: 'title'
end
end
class GoogleCloudManagedidentitiesV1OpMetadata
# @private
class Representation < Google::Apis::Core::JsonRepresentation
property :api_version, as: 'apiVersion'
property :create_time, as: 'createTime'
property :end_time, as: 'endTime'
property :requested_cancellation, as: 'requestedCancellation'
property :target, as: 'target'
property :verb, as: 'verb'
end
end
class GoogleCloudManagedidentitiesV1alpha1OpMetadata
# @private
class Representation < Google::Apis::Core::JsonRepresentation
property :api_version, as: 'apiVersion'
property :create_time, as: 'createTime'
property :end_time, as: 'endTime'
property :requested_cancellation, as: 'requestedCancellation'
property :target, as: 'target'
property :verb, as: 'verb'
end
end
class GoogleCloudManagedidentitiesV1beta1OpMetadata
# @private
class Representation < Google::Apis::Core::JsonRepresentation
property :api_version, as: 'apiVersion'
property :create_time, as: 'createTime'
property :end_time, as: 'endTime'
property :requested_cancellation, as: 'requestedCancellation'
property :target, as: 'target'
property :verb, as: 'verb'
end
end
class GoogleCloudSaasacceleratorManagementProvidersV1Instance
# @private
class Representation < Google::Apis::Core::JsonRepresentation
property :consumer_defined_name, as: 'consumerDefinedName'
property :create_time, as: 'createTime'
hash :labels, as: 'labels'
hash :maintenance_policy_names, as: 'maintenancePolicyNames'
hash :maintenance_schedules, as: 'maintenanceSchedules', class: Google::Apis::ManagedidentitiesV1alpha1::GoogleCloudSaasacceleratorManagementProvidersV1MaintenanceSchedule, decorator: Google::Apis::ManagedidentitiesV1alpha1::GoogleCloudSaasacceleratorManagementProvidersV1MaintenanceSchedule::Representation
property :maintenance_settings, as: 'maintenanceSettings', class: Google::Apis::ManagedidentitiesV1alpha1::GoogleCloudSaasacceleratorManagementProvidersV1MaintenanceSettings, decorator: Google::Apis::ManagedidentitiesV1alpha1::GoogleCloudSaasacceleratorManagementProvidersV1MaintenanceSettings::Representation
property :name, as: 'name'
hash :producer_metadata, as: 'producerMetadata'
collection :provisioned_resources, as: 'provisionedResources', class: Google::Apis::ManagedidentitiesV1alpha1::GoogleCloudSaasacceleratorManagementProvidersV1ProvisionedResource, decorator: Google::Apis::ManagedidentitiesV1alpha1::GoogleCloudSaasacceleratorManagementProvidersV1ProvisionedResource::Representation
property :slm_instance_template, as: 'slmInstanceTemplate'
property :slo_metadata, as: 'sloMetadata', class: Google::Apis::ManagedidentitiesV1alpha1::GoogleCloudSaasacceleratorManagementProvidersV1SloMetadata, decorator: Google::Apis::ManagedidentitiesV1alpha1::GoogleCloudSaasacceleratorManagementProvidersV1SloMetadata::Representation
hash :software_versions, as: 'softwareVersions'
property :state, as: 'state'
property :tenant_project_id, as: 'tenantProjectId'
property :update_time, as: 'updateTime'
end
end
class GoogleCloudSaasacceleratorManagementProvidersV1MaintenanceSchedule
# @private
class Representation < Google::Apis::Core::JsonRepresentation
property :can_reschedule, as: 'canReschedule'
property :end_time, as: 'endTime'
property :rollout_management_policy, as: 'rolloutManagementPolicy'
property :schedule_deadline_time, as: 'scheduleDeadlineTime'
property :start_time, as: 'startTime'
end
end
class GoogleCloudSaasacceleratorManagementProvidersV1MaintenanceSettings
# @private
class Representation < Google::Apis::Core::JsonRepresentation
property :exclude, as: 'exclude'
hash :maintenance_policies, as: 'maintenancePolicies', class: Google::Apis::ManagedidentitiesV1alpha1::MaintenancePolicy, decorator: Google::Apis::ManagedidentitiesV1alpha1::MaintenancePolicy::Representation
end
end
class GoogleCloudSaasacceleratorManagementProvidersV1NodeSloMetadata
# @private
class Representation < Google::Apis::Core::JsonRepresentation
collection :exclusions, as: 'exclusions', class: Google::Apis::ManagedidentitiesV1alpha1::GoogleCloudSaasacceleratorManagementProvidersV1SloExclusion, decorator: Google::Apis::ManagedidentitiesV1alpha1::GoogleCloudSaasacceleratorManagementProvidersV1SloExclusion::Representation
property :location, as: 'location'
property :node_id, as: 'nodeId'
end
end
class GoogleCloudSaasacceleratorManagementProvidersV1ProvisionedResource
# @private
class Representation < Google::Apis::Core::JsonRepresentation
property :resource_type, as: 'resourceType'
property :resource_url, as: 'resourceUrl'
end
end
class GoogleCloudSaasacceleratorManagementProvidersV1SloEligibility
# @private
class Representation < Google::Apis::Core::JsonRepresentation
property :eligible, as: 'eligible'
property :reason, as: 'reason'
end
end
class GoogleCloudSaasacceleratorManagementProvidersV1SloExclusion
# @private
class Representation < Google::Apis::Core::JsonRepresentation
property :duration, as: 'duration'
property :reason, as: 'reason'
property :sli_name, as: 'sliName'
property :start_time, as: 'startTime'
end
end
class GoogleCloudSaasacceleratorManagementProvidersV1SloMetadata
# @private
class Representation < Google::Apis::Core::JsonRepresentation
property :eligibility, as: 'eligibility', class: Google::Apis::ManagedidentitiesV1alpha1::GoogleCloudSaasacceleratorManagementProvidersV1SloEligibility, decorator: Google::Apis::ManagedidentitiesV1alpha1::GoogleCloudSaasacceleratorManagementProvidersV1SloEligibility::Representation
collection :exclusions, as: 'exclusions', class: Google::Apis::ManagedidentitiesV1alpha1::GoogleCloudSaasacceleratorManagementProvidersV1SloExclusion, decorator: Google::Apis::ManagedidentitiesV1alpha1::GoogleCloudSaasacceleratorManagementProvidersV1SloExclusion::Representation
collection :nodes, as: 'nodes', class: Google::Apis::ManagedidentitiesV1alpha1::GoogleCloudSaasacceleratorManagementProvidersV1NodeSloMetadata, decorator: Google::Apis::ManagedidentitiesV1alpha1::GoogleCloudSaasacceleratorManagementProvidersV1NodeSloMetadata::Representation
property :tier, as: 'tier'
end
end
class ListDomainsResponse
# @private
class Representation < Google::Apis::Core::JsonRepresentation
collection :domains, as: 'domains', class: Google::Apis::ManagedidentitiesV1alpha1::Domain, decorator: Google::Apis::ManagedidentitiesV1alpha1::Domain::Representation
property :next_page_token, as: 'nextPageToken'
collection :unreachable, as: 'unreachable'
end
end
class ListLocationsResponse
# @private
class Representation < Google::Apis::Core::JsonRepresentation
collection :locations, as: 'locations', class: Google::Apis::ManagedidentitiesV1alpha1::Location, decorator: Google::Apis::ManagedidentitiesV1alpha1::Location::Representation
property :next_page_token, as: 'nextPageToken'
end
end
class ListOperationsResponse
# @private
class Representation < Google::Apis::Core::JsonRepresentation
property :next_page_token, as: 'nextPageToken'
collection :operations, as: 'operations', class: Google::Apis::ManagedidentitiesV1alpha1::Operation, decorator: Google::Apis::ManagedidentitiesV1alpha1::Operation::Representation
end
end
class ListSqlIntegrationsResponse
# @private
class Representation < Google::Apis::Core::JsonRepresentation
property :next_page_token, as: 'nextPageToken'
collection :sql_integrations, as: 'sqlIntegrations', class: Google::Apis::ManagedidentitiesV1alpha1::SqlIntegration, decorator: Google::Apis::ManagedidentitiesV1alpha1::SqlIntegration::Representation
collection :unreachable, as: 'unreachable'
end
end
class Location
# @private
class Representation < Google::Apis::Core::JsonRepresentation
property :display_name, as: 'displayName'
hash :labels, as: 'labels'
property :location_id, as: 'locationId'
hash :metadata, as: 'metadata'
property :name, as: 'name'
end
end
class MaintenancePolicy
# @private
class Representation < Google::Apis::Core::JsonRepresentation
property :create_time, as: 'createTime'
property :description, as: 'description'
hash :labels, as: 'labels'
property :name, as: 'name'
property :state, as: 'state'
property :update_policy, as: 'updatePolicy', class: Google::Apis::ManagedidentitiesV1alpha1::UpdatePolicy, decorator: Google::Apis::ManagedidentitiesV1alpha1::UpdatePolicy::Representation
property :update_time, as: 'updateTime'
end
end
class MaintenanceWindow
# @private
class Representation < Google::Apis::Core::JsonRepresentation
property :daily_cycle, as: 'dailyCycle', class: Google::Apis::ManagedidentitiesV1alpha1::DailyCycle, decorator: Google::Apis::ManagedidentitiesV1alpha1::DailyCycle::Representation
property :weekly_cycle, as: 'weeklyCycle', class: Google::Apis::ManagedidentitiesV1alpha1::WeeklyCycle, decorator: Google::Apis::ManagedidentitiesV1alpha1::WeeklyCycle::Representation
end
end
class Operation
# @private
class Representation < Google::Apis::Core::JsonRepresentation
property :done, as: 'done'
property :error, as: 'error', class: Google::Apis::ManagedidentitiesV1alpha1::Status, decorator: Google::Apis::ManagedidentitiesV1alpha1::Status::Representation
hash :metadata, as: 'metadata'
property :name, as: 'name'
hash :response, as: 'response'
end
end
class OperationMetadata
# @private
class Representation < Google::Apis::Core::JsonRepresentation
property :api_version, as: 'apiVersion'
property :cancel_requested, as: 'cancelRequested'
property :create_time, as: 'createTime'
property :end_time, as: 'endTime'
property :status_detail, as: 'statusDetail'
property :target, as: 'target'
property :verb, as: 'verb'
end
end
class Policy
# @private
class Representation < Google::Apis::Core::JsonRepresentation
collection :bindings, as: 'bindings', class: Google::Apis::ManagedidentitiesV1alpha1::Binding, decorator: Google::Apis::ManagedidentitiesV1alpha1::Binding::Representation
property :etag, :base64 => true, as: 'etag'
property :version, as: 'version'
end
end
class ReconfigureTrustRequest
# @private
class Representation < Google::Apis::Core::JsonRepresentation
property :trust_prop, as: 'trust', class: Google::Apis::ManagedidentitiesV1alpha1::TrustProp, decorator: Google::Apis::ManagedidentitiesV1alpha1::TrustProp::Representation
end
end
class ResetAdminPasswordRequest
# @private
class Representation < Google::Apis::Core::JsonRepresentation
end
end
class ResetAdminPasswordResponse
# @private
class Representation < Google::Apis::Core::JsonRepresentation
property :password, as: 'password'
end
end
class SqlIntegration
# @private
class Representation < Google::Apis::Core::JsonRepresentation
property :create_time, as: 'createTime'
property :name, as: 'name'
property :sql_instance, as: 'sqlInstance'
property :state, as: 'state'
property :update_time, as: 'updateTime'
end
end
class Schedule
# @private
class Representation < Google::Apis::Core::JsonRepresentation
property :day, as: 'day'
property :duration, as: 'duration'
property :start_time, as: 'startTime', class: Google::Apis::ManagedidentitiesV1alpha1::TimeOfDay, decorator: Google::Apis::ManagedidentitiesV1alpha1::TimeOfDay::Representation
end
end
class SetIamPolicyRequest
# @private
class Representation < Google::Apis::Core::JsonRepresentation
property :policy, as: 'policy', class: Google::Apis::ManagedidentitiesV1alpha1::Policy, decorator: Google::Apis::ManagedidentitiesV1alpha1::Policy::Representation
end
end
class Status
# @private
class Representation < Google::Apis::Core::JsonRepresentation
property :code, as: 'code'
collection :details, as: 'details'
property :message, as: 'message'
end
end
class TestIamPermissionsRequest
# @private
class Representation < Google::Apis::Core::JsonRepresentation
collection :permissions, as: 'permissions'
end
end
class TestIamPermissionsResponse
# @private
class Representation < Google::Apis::Core::JsonRepresentation
collection :permissions, as: 'permissions'
end
end
class TimeOfDay
# @private
class Representation < Google::Apis::Core::JsonRepresentation
property :hours, as: 'hours'
property :minutes, as: 'minutes'
property :nanos, as: 'nanos'
property :seconds, as: 'seconds'
end
end
class TrustProp
# @private
class Representation < Google::Apis::Core::JsonRepresentation
property :create_time, as: 'createTime'
property :last_known_trust_connected_heartbeat_time, as: 'lastKnownTrustConnectedHeartbeatTime'
property :selective_authentication, as: 'selectiveAuthentication'
property :state, as: 'state'
property :state_description, as: 'stateDescription'
collection :target_dns_ip_addresses, as: 'targetDnsIpAddresses'
property :target_domain_name, as: 'targetDomainName'
property :trust_direction, as: 'trustDirection'
property :trust_handshake_secret, as: 'trustHandshakeSecret'
property :trust_type, as: 'trustType'
property :update_time, as: 'updateTime'
end
end
class UpdatePolicy
# @private
class Representation < Google::Apis::Core::JsonRepresentation
property :channel, as: 'channel'
collection :deny_maintenance_periods, as: 'denyMaintenancePeriods', class: Google::Apis::ManagedidentitiesV1alpha1::DenyMaintenancePeriod, decorator: Google::Apis::ManagedidentitiesV1alpha1::DenyMaintenancePeriod::Representation
property :window, as: 'window', class: Google::Apis::ManagedidentitiesV1alpha1::MaintenanceWindow, decorator: Google::Apis::ManagedidentitiesV1alpha1::MaintenanceWindow::Representation
end
end
class ValidateTrustRequest
# @private
class Representation < Google::Apis::Core::JsonRepresentation
property :trust_prop, as: 'trust', class: Google::Apis::ManagedidentitiesV1alpha1::TrustProp, decorator: Google::Apis::ManagedidentitiesV1alpha1::TrustProp::Representation
end
end
class WeeklyCycle
# @private
class Representation < Google::Apis::Core::JsonRepresentation
collection :schedule, as: 'schedule', class: Google::Apis::ManagedidentitiesV1alpha1::Schedule, decorator: Google::Apis::ManagedidentitiesV1alpha1::Schedule::Representation
end
end
end
end
end
| 39.526316 | 323 | 0.668609 |
015484385942bca916fc9e9e1a43a08e956d7b45 | 365 | after "development:sites" do
site1 = Site.find_by!(name: "site1")
site1.participants.create!(
name: "name11",
summary: "summary11",
description: <<~EOS
# Hello
description11
EOS
)
site1.participants.create!(
name: "name12",
summary: "summary12",
description: <<~EOS
# Hello
description12
EOS
)
end
| 17.380952 | 38 | 0.6 |
21b9dbb059024562d35ddb6b855922d9880e24b7 | 559 | class BrewCask < Formula
homepage "https://github.com/caskroom/homebrew-cask/"
url "https://github.com/caskroom/homebrew-cask.git", tag: "v0.60.1"
depends_on ruby: "2.0"
UNINSTALL_MSG = <<-EOS.undent
You must uninstall this formula. It is no longer needed to stay up to date,
as Homebrew now takes care of that automatically.
EOS
def install
(buildpath / "UPGRADE").write UNINSTALL_MSG
prefix.install "UPGRADE"
end
def caveats
UNINSTALL_MSG
end
test do
system "brew", "cask", "info", "google-chrome"
end
end
| 22.36 | 79 | 0.690519 |
6adc9182fa8ebe37c62addb044524a702251fd99 | 524 | require 'spec_helper'
describe UserUploader do
include CarrierWave::Test::Matchers
let(:user){ FactoryGirl.create(:user) }
before do
UserUploader.enable_processing = true
@uploader = UserUploader.new(user, :uploaded_image)
@uploader.store!(File.open("#{Rails.root}/spec/fixtures/image.png"))
end
after do
UserUploader.enable_processing = false
@uploader.remove!
end
describe '#thumb_avatar' do
subject{ @uploader.thumb_avatar }
it{ should have_dimensions(119, 121) }
end
end
| 21.833333 | 72 | 0.715649 |
ed15a8083c851636ef7460289ccb739093871d5c | 1,424 | require 'rails_helper'
RSpec.feature 'Public Recipes #Index', type: :feature do
background do
visit new_user_session_path
@first_user = User.create(name: 'Mark', email: 'mark@gmail.com', password: '0123456', confirmed_at: Time.now)
@second_user = User.create(name: 'Griifin', email: 'punk@gmail.com', password: '0123456', confirmed_at: Time.now)
@mark_recipe = Recipe.create(name: 'mark special', prep_time: 2,
cook_time: 2, description: 'Mark Mark Mark',
user: @first_user, public: false)
@griifin_recipe = Recipe.create(name: 'Griifin special', prep_time: 3,
cook_time: 3, description: 'Griifin Griifin Griifin',
user: @second_user, public: true)
fill_in 'user_email', with: @second_user.email
fill_in 'user_password', with: @second_user.password
click_button 'Log in'
visit public_recipes_path
end
it 'sees recipe name' do
expect(page).to have_content('Griifin special')
end
it 'sees recipe destription' do
expect(page).to have_content('Griifin Griifin Griifin')
end
it 'sees recipe owner' do
expect(page).to have_content('Griifin')
end
it 'redirects correctly to the recipes detail link' do
click_link @griifin_recipe.name
expect(page).to have_current_path(recipe_path(@griifin_recipe.id))
end
end
| 35.6 | 117 | 0.654494 |
38b3057db9b57ed826f7f82722ced978bffaf8a7 | 219 | class CreateAttachments < ActiveRecord::Migration[4.2]
def change
create_table :attachments do |t|
t.references :advent_calendar_item, index: true
t.string :image
t.timestamps
end
end
end
| 19.909091 | 54 | 0.694064 |
1ac4f1ba01bd6d47ec90123b234e0fe3282b0ba5 | 383 | module LearningSystem
module UserSamples
def good_users
[
User.new("tom", "b4dp4ss"),
User.new('Tomm', 'NotS3cure'),
]
end
def bad_users
[
User.new('Pete', ''),
User.new('', ''),
User.new('', 'b43'),
User.new('Timothy', 'Withwaytolooooooooooongpassword'),
]
end
end
end
| 19.15 | 65 | 0.480418 |
b95cc2f694eb0a163086f7d40e8c0f2b8dd3f2bd | 189 | class UpdateCustomerItem < ActiveRecord::Migration[5.2]
def change
add_column :customer_items, :room_number, :string
add_column :customer_items, :quantity_bed, :decimal
end
end
| 27 | 55 | 0.767196 |
621cd772b042840a56c4baf6d3971418cd3634bb | 24,091 | # This tests the Hyrax::WorksControllerBehavior module
# which is included into .internal_test_app/app/controllers/hyrax/generic_works_controller.rb
RSpec.describe Hyrax::GenericWorksController do
routes { Rails.application.routes }
let(:main_app) { Rails.application.routes.url_helpers }
let(:hyrax) { Hyrax::Engine.routes.url_helpers }
let(:user) { create(:user) }
before { sign_in user }
describe 'integration test for suppressed documents' do
let(:work) do
create(:work, :public, state: Vocab::FedoraResourceStatus.inactive)
end
before do
create(:sipity_entity, proxy_for_global_id: work.to_global_id.to_s)
end
it 'renders the unavailable message because it is in workflow' do
get :show, params: { id: work }
expect(response.code).to eq '401'
expect(response).to render_template(:unavailable)
expect(assigns[:presenter]).to be_instance_of Hyrax::GenericWorkPresenter
expect(flash[:notice]).to eq 'The work is not currently available because it has not yet completed the approval process'
end
end
describe 'integration test for depositor of a suppressed documents without a workflow role' do
let(:work) do
create(:work, :public, state: Vocab::FedoraResourceStatus.inactive, user: user)
end
before do
create(:sipity_entity, proxy_for_global_id: work.to_global_id.to_s)
end
it 'renders without the unauthorized message' do
get :show, params: { id: work.id }
expect(response.code).to eq '200'
expect(response).to render_template(:show)
expect(assigns[:presenter]).to be_instance_of Hyrax::GenericWorkPresenter
expect(flash[:notice]).to be_nil
end
end
describe '#show' do
before do
create(:sipity_entity, proxy_for_global_id: work.to_global_id.to_s)
end
context 'while logged out' do
let(:work) { create(:public_generic_work, user: user, title: ['public thing']) }
before { sign_out user }
context "without a referer" do
it "sets the default breadcrumbs" do
expect(controller).to receive(:add_breadcrumb).with('Home', Hyrax::Engine.routes.url_helpers.root_path(locale: 'en'))
get :show, params: { id: work }
expect(response).to be_successful
end
end
context "with a referer" do
before do
request.env['HTTP_REFERER'] = 'http://test.host/foo'
end
it "sets breadcrumbs to authorized pages" do
expect(controller).to receive(:add_breadcrumb).with('Home', main_app.root_path(locale: 'en'))
expect(controller).not_to receive(:add_breadcrumb).with('Dashboard', hyrax.dashboard_path(locale: 'en'))
expect(controller).not_to receive(:add_breadcrumb).with('Your Works', hyrax.my_works_path(locale: 'en'))
expect(controller).to receive(:add_breadcrumb).with('public thing', main_app.hyrax_generic_work_path(work.id, locale: 'en'))
get :show, params: { id: work }
expect(response).to be_successful
expect(response).to render_template("layouts/hyrax/1_column")
end
end
end
context 'my own private work' do
let(:work) { create(:private_generic_work, user: user, title: ['test title']) }
it 'shows me the page' do
get :show, params: { id: work }
expect(response).to be_success
expect(assigns(:presenter)).to be_kind_of Hyrax::WorkShowPresenter
end
context "without a referer" do
it "sets breadcrumbs" do
expect(controller).to receive(:add_breadcrumb).with('Home', Hyrax::Engine.routes.url_helpers.root_path(locale: 'en'))
expect(controller).to receive(:add_breadcrumb).with("Dashboard", hyrax.dashboard_path(locale: 'en'))
get :show, params: { id: work }
expect(response).to be_successful
end
end
context "with a referer" do
before do
request.env['HTTP_REFERER'] = 'http://test.host/foo'
end
it "sets breadcrumbs" do
expect(controller).to receive(:add_breadcrumb).with('Home', Hyrax::Engine.routes.url_helpers.root_path(locale: 'en'))
expect(controller).to receive(:add_breadcrumb).with('Dashboard', hyrax.dashboard_path(locale: 'en'))
expect(controller).to receive(:add_breadcrumb).with('Works', hyrax.my_works_path(locale: 'en'))
expect(controller).to receive(:add_breadcrumb).with('test title', main_app.hyrax_generic_work_path(work.id, locale: 'en'))
get :show, params: { id: work }
expect(response).to be_successful
expect(response).to render_template("layouts/hyrax/1_column")
end
end
context "with a parent work" do
let(:parent) { create(:generic_work, title: ['Parent Work'], user: user, ordered_members: [work]) }
before do
create(:sipity_entity, proxy_for_global_id: parent.to_global_id.to_s)
end
it "sets the parent presenter" do
get :show, params: { id: work, parent_id: parent }
expect(response).to be_success
expect(assigns[:parent_presenter]).to be_instance_of Hyrax::GenericWorkPresenter
end
end
context "with an endnote file" do
let(:disposition) { response.header.fetch("Content-Disposition") }
let(:content_type) { response.header.fetch("Content-Type") }
render_views
it 'downloads the file' do
get :show, params: { id: work, format: 'endnote' }
expect(response).to be_successful
expect(disposition).to include("attachment")
expect(content_type).to eq("application/x-endnote-refer")
expect(response.body).to include("%T test title")
end
end
end
context 'someone elses private work' do
let(:work) { create(:private_generic_work) }
it 'shows unauthorized message' do
get :show, params: { id: work }
expect(response.code).to eq '401'
expect(response).to render_template(:unauthorized)
end
end
context 'someone else\'s public work' do
let(:work) { create(:public_generic_work) }
context "html" do
it 'shows me the page' do
expect(controller). to receive(:additional_response_formats).with(ActionController::MimeResponds::Collector)
get :show, params: { id: work }
expect(response).to be_success
end
end
context "ttl" do
let(:presenter) { double }
before do
allow(controller).to receive(:presenter).and_return(presenter)
allow(presenter).to receive(:export_as_ttl).and_return("ttl graph")
allow(presenter).to receive(:editor?).and_return(true)
end
it 'renders a turtle file' do
get :show, params: { id: '99999999', format: :ttl }
expect(response).to be_successful
expect(response.body).to eq "ttl graph"
expect(response.content_type).to eq 'text/turtle'
end
end
end
context 'when I am a repository manager' do
before { allow(::User.group_service).to receive(:byname).and_return(user.user_key => ['admin']) }
let(:work) { create(:private_generic_work) }
it 'someone elses private work should show me the page' do
get :show, params: { id: work }
expect(response).to be_success
end
end
context 'with work still in workflow' do
before do
allow(controller).to receive(:search_results).and_return([nil, document_list])
end
let(:work) { instance_double(GenericWork, id: '99999', to_global_id: '99999') }
context 'with a user lacking both workflow permission and read access' do
before do
allow(SolrDocument).to receive(:find).and_return(document)
allow(controller.current_ability).to receive(:can?).with(:read, document).and_return(false)
end
let(:document_list) { [] }
let(:document) { instance_double(SolrDocument, suppressed?: true) }
it 'shows the unauthorized message' do
get :show, params: { id: work.id }
expect(response.code).to eq '401'
expect(response).to render_template(:unauthorized)
end
context 'with a user who lacks workflow permission but has read access' do
before do
allow(SolrDocument).to receive(:find).and_return(document)
allow(controller.current_ability).to receive(:can?).with(:read, document).and_return(true)
end
let(:document_list) { [] }
let(:document) { instance_double(SolrDocument, suppressed?: true) }
it 'shows the unavailable message' do
get :show, params: { id: work.id }
expect(response.code).to eq '401'
expect(response).to render_template(:unavailable)
expect(flash[:notice]).to eq 'The work is not currently available because it has not yet completed the approval process'
end
end
end
context 'with a user granted workflow permission' do
let(:document_list) { [document] }
let(:document) { instance_double(SolrDocument) }
it 'renders without the unauthorized message' do
get :show, params: { id: work.id }
expect(response.code).to eq '200'
expect(response).to render_template(:show)
expect(flash[:notice]).to be_nil
end
end
end
end
describe '#new' do
context 'my work' do
it 'shows me the page' do
get :new
expect(response).to be_success
expect(assigns[:form]).to be_kind_of Hyrax::GenericWorkForm
expect(assigns[:form].depositor).to eq user.user_key
expect(assigns[:curation_concern]).to be_kind_of GenericWork
expect(assigns[:curation_concern].depositor).to eq user.user_key
expect(response).to render_template("layouts/hyrax/dashboard")
end
end
end
describe '#create' do
let(:actor) { double(create: create_status) }
let(:create_status) { true }
before do
allow(Hyrax::CurationConcern).to receive(:actor).and_return(actor)
end
context 'when create is successful' do
let(:work) { stub_model(GenericWork) }
it 'creates a work' do
allow(controller).to receive(:curation_concern).and_return(work)
post :create, params: { generic_work: { title: ['a title'] } }
expect(response).to redirect_to main_app.hyrax_generic_work_path(work, locale: 'en')
end
end
context 'when create fails' do
let(:work) { create(:work) }
let(:create_status) { false }
it 'draws the form again' do
post :create, params: { generic_work: { title: ['a title'] } }
expect(response.status).to eq 422
expect(assigns[:form]).to be_kind_of Hyrax::GenericWorkForm
expect(response).to render_template 'new'
end
end
context 'when not authorized' do
before { allow(controller.current_ability).to receive(:can?).and_return(false) }
it 'shows the unauthorized message' do
post :create, params: { generic_work: { title: ['a title'] } }
expect(response.code).to eq '401'
expect(response).to render_template(:unauthorized)
end
end
context "with files" do
let(:actor) { double('An actor') }
let(:work) { create(:work) }
before do
allow(controller).to receive(:actor).and_return(actor)
# Stub out the creation of the work so we can redirect somewhere
allow(controller).to receive(:curation_concern).and_return(work)
end
it "attaches files" do
expect(actor).to receive(:create)
.with(Hyrax::Actors::Environment) do |env|
expect(env.attributes.keys).to include('uploaded_files')
end
.and_return(true)
post :create, params: {
generic_work: {
title: ["First title"],
visibility: 'open'
},
uploaded_files: ['777', '888']
}
expect(flash[:notice]).to be_html_safe
expect(flash[:notice]).to eq "Your files are being processed by Hyrax in the background. " \
"The metadata and access controls you specified are being applied. " \
"You may need to refresh this page to see these updates."
expect(response).to redirect_to main_app.hyrax_generic_work_path(work, locale: 'en')
end
context "from browse everything" do
let(:url1) { "https://dl.dropbox.com/fake/blah-blah.filepicker-demo.txt.txt" }
let(:url2) { "https://dl.dropbox.com/fake/blah-blah.Getting%20Started.pdf" }
let(:browse_everything_params) do
{ "0" => { "url" => url1,
"expires" => "2014-03-31T20:37:36.214Z",
"file_name" => "filepicker-demo.txt.txt" },
"1" => { "url" => url2,
"expires" => "2014-03-31T20:37:36.731Z",
"file_name" => "Getting+Started.pdf" } }.with_indifferent_access
end
let(:uploaded_files) do
browse_everything_params.values.map { |v| v['url'] }
end
context "For a batch upload" do
# TODO: move this to batch_uploads controller
it "ingests files from provide URLs" do
skip "Creating a FileSet without a parent work is not yet supported"
expect(ImportUrlJob).to receive(:perform_later).twice
expect do
post :create, params: { selected_files: browse_everything_params, file_set: {} }
end.to change(FileSet, :count).by(2)
created_files = FileSet.all
expect(created_files.map(&:import_url)).to include(url1, url2)
expect(created_files.map(&:label)).to include("filepicker-demo.txt.txt", "Getting+Started.pdf")
end
end
context "when a work id is passed" do
let(:work) do
create(:work, user: user, title: ['test title'])
end
it "records the work" do
# TODO: ensure the actor stack, called with these params
# makes one work, two file sets and calls ImportUrlJob twice.
expect(actor).to receive(:create).with(Hyrax::Actors::Environment) do |env|
expect(env.attributes['uploaded_files']).to eq []
expect(env.attributes['remote_files']).to eq browse_everything_params.values
end
post :create, params: {
selected_files: browse_everything_params,
uploaded_files: uploaded_files,
parent_id: work.id,
generic_work: { title: ['First title'] }
}
expect(flash[:notice]).to eq "Your files are being processed by Hyrax in the background. " \
"The metadata and access controls you specified are being applied. " \
"You may need to refresh this page to see these updates."
expect(response).to redirect_to main_app.hyrax_generic_work_path(work, locale: 'en')
end
end
end
end
end
describe '#edit' do
context 'my own private work' do
let(:work) { create(:private_generic_work, user: user) }
it 'shows me the page and sets breadcrumbs' do
expect(controller).to receive(:add_breadcrumb).with("Home", root_path(locale: 'en'))
expect(controller).to receive(:add_breadcrumb).with("Dashboard", hyrax.dashboard_path(locale: 'en'))
expect(controller).to receive(:add_breadcrumb).with("Works", hyrax.my_works_path(locale: 'en'))
expect(controller).to receive(:add_breadcrumb).with(work.title.first, main_app.hyrax_generic_work_path(work.id, locale: 'en'))
expect(controller).to receive(:add_breadcrumb).with('Edit', main_app.edit_hyrax_generic_work_path(work.id))
get :edit, params: { id: work }
expect(response).to be_success
expect(assigns[:form]).to be_kind_of Hyrax::GenericWorkForm
expect(response).to render_template("layouts/hyrax/dashboard")
end
end
context 'someone elses private work' do
routes { Rails.application.class.routes }
let(:work) { create(:private_generic_work) }
it 'shows the unauthorized message' do
get :edit, params: { id: work }
expect(response.code).to eq '401'
expect(response).to render_template(:unauthorized)
end
end
context 'someone elses public work' do
let(:work) { create(:public_generic_work) }
it 'shows the unauthorized message' do
get :edit, params: { id: work }
expect(response.code).to eq '401'
expect(response).to render_template(:unauthorized)
end
end
context 'when I am a repository manager' do
before { allow(::User.group_service).to receive(:byname).and_return(user.user_key => ['admin']) }
let(:work) { create(:private_generic_work) }
it 'someone elses private work should show me the page' do
get :edit, params: { id: work }
expect(response).to be_success
end
end
end
describe '#update' do
let(:work) { stub_model(GenericWork) }
let(:visibility_changed) { false }
let(:actor) { double(update: true) }
before do
allow(Hyrax::CurationConcern).to receive(:actor).and_return(actor)
allow(GenericWork).to receive(:find).and_return(work)
allow(work).to receive(:visibility_changed?).and_return(visibility_changed)
end
context "when the user has write access to the file" do
before do
allow(controller).to receive(:authorize!).with(:update, work).and_return(true)
end
context "when the work has no file sets" do
it 'updates the work' do
patch :update, params: { id: work, generic_work: {} }
expect(response).to redirect_to main_app.hyrax_generic_work_path(work, locale: 'en')
end
end
context "when the work has file sets attached" do
before do
allow(work).to receive(:file_sets).and_return(double(present?: true))
end
it 'updates the work' do
patch :update, params: { id: work, generic_work: {} }
expect(response).to redirect_to main_app.hyrax_generic_work_path(work, locale: 'en')
end
end
it "can update file membership" do
patch :update, params: { id: work, generic_work: { ordered_member_ids: ['foo_123'] } }
expect(actor).to have_received(:update).with(Hyrax::Actors::Environment) do |env|
expect(env.attributes).to eq("ordered_member_ids" => ['foo_123'],
"remote_files" => [],
"uploaded_files" => [])
end
end
describe 'changing rights' do
let(:visibility_changed) { true }
let(:actor) { double(update: true) }
context 'when the work has file sets attached' do
before do
allow(work).to receive(:file_sets).and_return(double(present?: true))
end
it 'prompts to change the files access' do
patch :update, params: { id: work, generic_work: {} }
expect(response).to redirect_to main_app.confirm_hyrax_permission_path(controller.curation_concern, locale: 'en')
end
end
context 'when the work has no file sets' do
it "doesn't prompt to change the files access" do
patch :update, params: { id: work, generic_work: {} }
expect(response).to redirect_to main_app.hyrax_generic_work_path(work, locale: 'en')
end
end
end
describe 'update failed' do
let(:actor) { double(update: false) }
it 'renders the form' do
patch :update, params: { id: work, generic_work: {} }
expect(assigns[:form]).to be_kind_of Hyrax::GenericWorkForm
expect(response).to render_template('edit')
end
end
end
context 'someone elses public work' do
let(:work) { create(:public_generic_work) }
it 'shows the unauthorized message' do
get :update, params: { id: work }
expect(response.code).to eq '401'
expect(response).to render_template(:unauthorized)
end
end
context 'when I am a repository manager' do
before { allow(::User.group_service).to receive(:byname).and_return(user.user_key => ['admin']) }
let(:work) { create(:private_generic_work) }
it 'someone elses private work should update the work' do
patch :update, params: { id: work, generic_work: {} }
expect(response).to redirect_to main_app.hyrax_generic_work_path(work, locale: 'en')
end
end
end
describe '#destroy' do
let(:work_to_be_deleted) { create(:private_generic_work, user: user) }
let(:parent_collection) { create(:collection) }
it 'deletes the work' do
delete :destroy, params: { id: work_to_be_deleted }
expect(response).to redirect_to Hyrax::Engine.routes.url_helpers.my_works_path(locale: 'en')
expect(GenericWork).not_to exist(work_to_be_deleted.id)
end
context "when work is a member of a collection" do
before do
parent_collection.members = [work_to_be_deleted]
parent_collection.save!
end
it 'deletes the work and updates the parent collection' do
delete :destroy, params: { id: work_to_be_deleted }
expect(GenericWork).not_to exist(work_to_be_deleted.id)
expect(response).to redirect_to Hyrax::Engine.routes.url_helpers.my_works_path(locale: 'en')
expect(parent_collection.reload.members).to eq []
end
end
it "invokes the after_destroy callback" do
expect(Hyrax.config.callback).to receive(:run)
.with(:after_destroy, work_to_be_deleted.id, user)
delete :destroy, params: { id: work_to_be_deleted }
end
context 'someone elses public work' do
let(:work_to_be_deleted) { create(:private_generic_work) }
it 'shows unauthorized message' do
delete :destroy, params: { id: work_to_be_deleted }
expect(response.code).to eq '401'
expect(response).to render_template(:unauthorized)
end
end
context 'when I am a repository manager' do
let(:work_to_be_deleted) { create(:private_generic_work) }
before { allow(::User.group_service).to receive(:byname).and_return(user.user_key => ['admin']) }
it 'someone elses private work should delete the work' do
delete :destroy, params: { id: work_to_be_deleted }
expect(GenericWork).not_to exist(work_to_be_deleted.id)
end
end
end
describe '#file_manager' do
let(:work) { create(:private_generic_work, user: user) }
before do
create(:sipity_entity, proxy_for_global_id: work.to_global_id.to_s)
end
it "is successful" do
get :file_manager, params: { id: work.id }
expect(response).to be_success
expect(assigns(:form)).not_to be_blank
end
end
describe '#manifest' do
let(:work) { create(:work_with_one_file, user: user) }
let(:file_set) { work.ordered_members.to_a.first }
let(:manifest_factory) { double(to_h: { test: 'manifest' }) }
before do
Hydra::Works::AddFileToFileSet.call(file_set,
File.open(fixture_path + '/world.png'),
:original_file)
allow(IIIFManifest::ManifestFactory).to receive(:new)
.with(Hyrax::WorkShowPresenter)
.and_return(manifest_factory)
end
it "produces a manifest for a json request" do
get :manifest, params: { id: work, format: :json }
expect(response.body).to eq "{\"test\":\"manifest\"}"
end
it "produces a manifest for a html request" do
get :manifest, params: { id: work, format: :html }
expect(response.body).to eq "{\"test\":\"manifest\"}"
end
end
end
| 38.669342 | 134 | 0.631481 |
184f89200ab89a6beae34f232304b2cd19c096a1 | 2,459 | # frozen_string_literal: true
module API
class ProjectExport < ::API::Base
helpers Helpers::RateLimiter
before do
not_found! unless Gitlab::CurrentSettings.project_export_enabled?
authorize_admin_project
end
params do
requires :id, type: String, desc: 'The ID of a project'
end
resource :projects, requirements: { id: %r{[^/]+} } do
desc 'Get export status' do
detail 'This feature was introduced in GitLab 10.6.'
success Entities::ProjectExportStatus
end
get ':id/export' do
present user_project, with: Entities::ProjectExportStatus
end
desc 'Download export' do
detail 'This feature was introduced in GitLab 10.6.'
end
get ':id/export/download' do
check_rate_limit! :project_download_export, [current_user, user_project]
if user_project.export_file_exists?
present_carrierwave_file!(user_project.export_file)
else
render_api_error!('404 Not found or has expired', 404)
end
end
desc 'Start export' do
detail 'This feature was introduced in GitLab 10.6.'
end
params do
optional :description, type: String, desc: 'Override the project description'
optional :upload, type: Hash do
optional :url, type: String, desc: 'The URL to upload the project'
optional :http_method, type: String, default: 'PUT', desc: 'HTTP method to upload the exported project'
end
end
post ':id/export' do
check_rate_limit! :project_export, [current_user]
user_project.remove_exports
project_export_params = declared_params(include_missing: false)
after_export_params = project_export_params.delete(:upload) || {}
export_strategy = if after_export_params[:url].present?
params = after_export_params.slice(:url, :http_method).symbolize_keys
Gitlab::ImportExport::AfterExportStrategies::WebUploadStrategy.new(**params)
end
if export_strategy&.invalid?
render_validation_error!(export_strategy)
else
user_project.add_export_job(current_user: current_user,
after_export_strategy: export_strategy,
params: project_export_params)
end
accepted!
end
end
end
end
| 33.22973 | 113 | 0.632778 |
26856748273ec5c7047ebf5086e9da106fe0b74b | 2,103 | require_relative "spec_helper"
require 'pry'
describe "User" do
describe 'User basics' do
it "cannot be saved without password" do
@user = User.new
@user.username = "Bob"
expect(@user.save).to eq(false)
end
it "has many tools" do
@user = User.create(username: "John", password: "abc123")
@drill = Tool.create
@hammer = Tool.create
@hammer.user_id = @user.id
@hammer.save
expect(@user.tools).to include(@hammer)
end
it "does not allow two Users to have the same username" do
@user = User.create(username: "John", email: "jj1990@gmail.com", password: "abc123")
params = {
:username => "John",
:email => "skittles@aol.com",
:password => "rainbows"
}
post '/signup', params
expect(last_response.location).to include("/")
end
end
describe 'User/Contract associations' do
before :each do
%w(peter ben brian).each do |x|
eval "@#{x} = User.new; @#{x}.username = '#{x}'; @#{x}.password = '123'; @#{x}.save"
end
@contract = Contract.create
@drill = Tool.create(name: "drill", description: "cordless dewalt")
end
it "can be added to Contract as loaner" do
@contract.loaner = @peter
expect(@contract.loaner).to eq(@peter)
end
it "can be added to Contract as borrower" do
@contract.borrower = @ben
expect(@contract.borrower).to eq(@ben)
end
it "a User's loaners array is updated when User has been added to a Contract as a Borrower" do
@contract.borrower = @brian
@contract.loaner = @peter
@contract.save
expect(@brian.loaners).to include(@peter)
end
it "a User's borrowers array is updated when User has been added to a Contract as a Loaner" do
@contract.borrower = @ben
@contract.loaner = @peter
@contract.save
binding.pry
expect(@peter.borrowers).to include(@ben)
end
end
end
describe 'Contract' do
it "Defaults to 'active' status upon creation" do
@contract = Contract.create
expect(@contract.active).to eq(true)
end
it "Can change from active to inactive" do
@contract = Contract.create
@contract.terminate
expect(@contract.active).to eq(false)
end
end | 24.453488 | 95 | 0.675226 |
397615e4f7e01ac9c9e577d7700294b083d66258 | 1,526 | class UserController < ApplicationController
before_filter :require_user, :only => [:edit, :update, :destroy]
def index
end
def dashboard
@user = User.find(current_user)
end
def favorites
@user = User.find(current_user)
end
def friends
@user = User.find(current_user)
end
def managegroups
@user = User.find(current_user)
end
def manageprojects
@user = User.find(current_user)
end
def manageevents
@user = User.find(current_user)
end
def user
@users = User.all
@videos = Video.all
end
def show
@user = User.find(params[:id])
@friend = User.find_by_id(params[:name])
end
def create
@user = User.new(user_params)
respond_to do |format|
if @user.save
# Sends email to user when user is created.
ExampleMailer.registration_confirmation(@user).deliver
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
def update
if @user.update(user_params)
redirect_to @user, notice: "Update positive"
else
render 'edit'
end
end
private
def require_user
@user = User.find_by_id(params[:id])
redirect_to(request.referrer || root_path) unless current_user == @user
end
def user_params
params.require(:user).permit(:avatar, :description, :friendships, :name)
end
end
| 19.075 | 82 | 0.679554 |
6a81485b8dee3cb5c9d0ff070fad2a7ebb91d887 | 2,431 | class GitFtp < Formula
desc "Git-powered FTP client"
homepage "https://git-ftp.github.io/"
url "https://github.com/git-ftp/git-ftp/archive/1.6.0.tar.gz"
sha256 "088b58d66c420e5eddc51327caec8dcbe8bddae557c308aa739231ed0490db01"
license "GPL-3.0"
head "https://github.com/git-ftp/git-ftp.git", branch: "develop"
bottle do
sha256 cellar: :any, arm64_big_sur: "22f0e6b0a0c16aa110711333e1a44b77d65fe851049db51fb200f33a2e2be534"
sha256 cellar: :any, big_sur: "2e3d8573c71ae26fdac0d0d8952e625b5a14d90118a6a413604eac8c3a6f6eb6"
sha256 cellar: :any, catalina: "0a61ca11e69370dfecfd3c82d6d03aeec377bf9db660658403556ea71b84bae0"
sha256 cellar: :any, mojave: "f878c4015697794bb8b2c3f034a167b750d3871c0d320d903536128f01880ca2"
sha256 cellar: :any, high_sierra: "63c8b94fd89eb635d8c2056efdf933de45dca7fdb04793b620750f8b338fbb88"
sha256 cellar: :any_skip_relocation, x86_64_linux: "fb75d2375209ab69ec41dec62ec6715ebc0ba21f442313a2a6173df976c418ab"
end
depends_on "pandoc" => :build
depends_on "libssh2"
uses_from_macos "zlib"
resource "curl" do
url "https://curl.se/download/curl-7.69.0.tar.bz2"
mirror "https://curl.askapache.com/curl-7.69.0.tar.bz2"
sha256 "668d451108a7316cff040b23c79bc766e7ed84122074e44f662b8982f2e76739"
end
def install
resource("curl").stage do
system "./configure", "--disable-debug",
"--disable-dependency-tracking",
"--disable-silent-rules",
"--prefix=#{libexec}",
"--disable-ares",
"--with-darwinssl",
"--with-libssh2",
"--without-brotli",
"--without-ca-bundle",
"--without-ca-path",
"--without-gssapi",
"--without-libmetalink",
"--without-librtmp"
system "make", "install"
end
system "make", "prefix=#{prefix}", "install"
system "make", "-C", "man", "man"
man1.install "man/git-ftp.1"
(libexec/"bin").install bin/"git-ftp"
(bin/"git-ftp").write_env_script(libexec/"bin/git-ftp", PATH: "#{libexec}/bin:$PATH")
end
test do
system bin/"git-ftp", "--help"
end
end
| 41.913793 | 122 | 0.599753 |
b9bcb9999080a08debec776480dab760b07a76f9 | 1,899 | class Questdb < Formula
desc "Time Series Database"
homepage "https://www.questdb.org"
url "https://www.questdb.org/download/questdb-1.0.4-bin.tar.gz"
sha256 "a8d907d88c5bf67aeb465540c7e16ad45eccd13d152b34cdcf4e5056ad908739"
bottle :unneeded
depends_on :java => "1.7+"
def install
rm_rf "questdb.exe"
libexec.install Dir["*"]
bin.install_symlink "#{libexec}/questdb.sh" => "questdb"
end
plist_options :manual => "questdb start"
def plist; <<-EOS.undent
<?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>
<dict>
<key>SuccessfulExit</key>
<false/>
</dict>
<key>Label</key>
<string>#{plist_name}</string>
<key>ProgramArguments</key>
<array>
<string>#{opt_bin}/questdb</string>
<string>start</string>
<string>-d</string>
<string>var/"questdb"</string>
<string>-n</string>
</array>
<key>RunAtLoad</key>
<true/>
<key>WorkingDirectory</key>
<string>#{var}/questdb</string>
<key>StandardErrorPath</key>
<string>#{var}/log/questdb.log</string>
<key>StandardOutPath</key>
<string>#{var}/log/questdb.log</string>
<key>SoftResourceLimits</key>
<dict>
<key>NumberOfFiles</key>
<integer>1024</integer>
</dict>
</dict>
</plist>
EOS
end
test do
mkdir_p testpath/"data"
begin
fork do
exec "#{bin}/questdb start -d #{testpath}/data"
end
sleep 2
output = shell_output("curl -Is localhost:9000/js?q=x")
sleep 1
assert_match /questDB/, output
ensure
system "#{bin}/questdb", "stop"
end
end
end
| 26.375 | 106 | 0.577146 |
081ecf1684ca49d6211ac1b0cdbe1c4bee1a870b | 356 | User.create(
email: "example@example.com",
password: 'password',
password_confirmation: 'password',
first_name: 'Developer',
last_name: "Admin",
organization: "My Organization",
city: "My City",
state: "My State",
zip: "12345",
role: :admin
)
puts "Default admin user created with email 'example@example.com' and password 'password'."
| 23.733333 | 91 | 0.69382 |
ab9bc69bb1bda38a79709e85720ab239a98b58c3 | 1,443 | class Document < ApplicationRecord
include Seek::Rdf::RdfGeneration
include Seek::BioSchema::Support
acts_as_asset
validates :projects, presence: true, projects: { self: true }
acts_as_doi_parent(child_accessor: :versions)
#don't add a dependent=>:destroy, as the content_blob needs to remain to detect future duplicates
has_one :content_blob, -> (r) { where('content_blobs.asset_version = ?', r.version) }, :as => :asset, :foreign_key => :asset_id
if Seek::Config.events_enabled
has_and_belongs_to_many :events
before_destroy {events.clear}
enforce_authorization_on_association :events, :view
else
def events
[]
end
def event_ids
[]
end
def event_ids= events_ids
end
end
explicit_versioning(version_column: 'version', sync_ignore_columns: ['doi']) do
acts_as_doi_mintable(proxy: :parent, general_type: 'Text')
acts_as_versioned_resource
acts_as_favouritable
has_one :content_blob, -> (r) { where('content_blobs.asset_version = ? AND content_blobs.asset_type = ?', r.version, r.parent.class.name) },
primary_key: :document_id, foreign_key: :asset_id
end
# Returns the columns to be shown on the table view for the resource
def columns_default
super + ['version']
end
def columns_allowed
columns_default + ['doi','license','last_used_at','other_creators']
end
def use_mime_type_for_avatar?
true
end
end
| 26.722222 | 144 | 0.712405 |
339dd04d8f3a37e717d0c219b92374b5f1094ce0 | 26 | module StalkeesHelper
end
| 8.666667 | 21 | 0.884615 |
629ccecc7ca20473fd88206bd57aee21f43aefae | 2,280 | module Roar
module JSON
module JSONAPI
# Instance method API for JSON API Documents representing a single Resource
#
# @api private
module SingleResource
# @see Document#to_hash
def to_hash(options = {})
document = super(Options::Include.(options, mappings))
unwrapped = options[:wrap] == false
resource = unwrapped ? document : document['data']
resource['type'] = JSONAPI::MemberName.(self.class.type)
links = Renderer::Links.new.(resource, options)
meta = render_meta(options)
resource.reject! do |_, v| v && v.empty? end
unless unwrapped
included = resource.delete('included')
HashUtils.store_if_any(document, 'included',
Fragment::Included.(included, options))
end
HashUtils.store_if_any(resource, 'links', links)
HashUtils.store_if_any(document, 'meta', meta)
document
end
private
def mappings
@mappings ||= begin
mappings = {}
mappings[:id] = find_id_mappings
mappings[:relationships] = find_relationship_mappings
mappings[:relationships]['_self'] = self.class.type
mappings
end
end
def find_id_mapping(klass)
self_id = klass.definitions.detect { |definition|
definition[:as] && definition[:as].(:value) == 'id'
}.name
end
def find_id_mappings
included_definitions = self.class.definitions['included'].representer_module.definitions
id_mappings = included_definitions.each_with_object({}) do |definition, hash|
hash[definition.name] = find_id_mapping(definition[:decorator])
end
id_mappings['_self'] = find_id_mapping(self.class)
id_mappings
end
def find_relationship_mappings
included_definitions = self.class.definitions['included'].representer_module.definitions
included_definitions.each_with_object({}) do |definition, hash|
hash[definition.name] = definition.representer_module.type
end
end
end
end
end
end
| 32.571429 | 98 | 0.594298 |
01a95c410b04cf10e039d28ae9eca29e8a72aefb | 2,982 | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::SingleLineBlockParams, :config do
let(:cop_config) do
{ 'Methods' =>
[{ 'reduce' => %w[a e] },
{ 'test' => %w[x y] }] }
end
it 'finds wrong argument names in calls with different syntax' do
expect_offense(<<~RUBY)
def m
[0, 1].reduce { |c, d| c + d }
^^^^^^ Name `reduce` block params `|a, e|`.
[0, 1].reduce{ |c, d| c + d }
^^^^^^ Name `reduce` block params `|a, e|`.
[0, 1].reduce(5) { |c, d| c + d }
^^^^^^ Name `reduce` block params `|a, e|`.
[0, 1].reduce(5){ |c, d| c + d }
^^^^^^ Name `reduce` block params `|a, e|`.
[0, 1].reduce (5) { |c, d| c + d }
^^^^^^ Name `reduce` block params `|a, e|`.
[0, 1].reduce(5) { |c, d| c + d }
^^^^^^ Name `reduce` block params `|a, e|`.
ala.test { |x, z| bala }
^^^^^^ Name `test` block params `|x, y|`.
end
RUBY
expect_correction(<<~RUBY)
def m
[0, 1].reduce { |a, e| a + e }
[0, 1].reduce{ |a, e| a + e }
[0, 1].reduce(5) { |a, e| a + e }
[0, 1].reduce(5){ |a, e| a + e }
[0, 1].reduce (5) { |a, e| a + e }
[0, 1].reduce(5) { |a, e| a + e }
ala.test { |x, y| bala }
end
RUBY
end
it 'allows calls with proper argument names' do
expect_no_offenses(<<~RUBY)
def m
[0, 1].reduce { |a, e| a + e }
[0, 1].reduce{ |a, e| a + e }
[0, 1].reduce(5) { |a, e| a + e }
[0, 1].reduce(5){ |a, e| a + e }
[0, 1].reduce (5) { |a, e| a + e }
[0, 1].reduce(5) { |a, e| a + e }
ala.test { |x, y| bala }
end
RUBY
end
it 'allows an unused parameter to have a leading underscore' do
expect_no_offenses('File.foreach(filename).reduce(0) { |a, _e| a + 1 }')
end
it 'finds incorrectly named parameters with leading underscores' do
expect_offense(<<~RUBY)
File.foreach(filename).reduce(0) { |_x, _y| }
^^^^^^^^ Name `reduce` block params `|_a, _e|`.
RUBY
expect_correction(<<~RUBY)
File.foreach(filename).reduce(0) { |_a, _e| }
RUBY
end
it 'ignores do..end blocks' do
expect_no_offenses(<<~RUBY)
def m
[0, 1].reduce do |c, d|
c + d
end
end
RUBY
end
it 'ignores :reduce symbols' do
expect_no_offenses(<<~RUBY)
def m
call_method(:reduce) { |a, b| a + b}
end
RUBY
end
it 'does not report when destructuring is used' do
expect_no_offenses(<<~RUBY)
def m
test.reduce { |a, (id, _)| a + id}
end
RUBY
end
it 'does not report if no block arguments are present' do
expect_no_offenses(<<~RUBY)
def m
test.reduce { true }
end
RUBY
end
end
| 28.132075 | 88 | 0.463447 |
e8e0c40273fea405faec3ae8bf16418487498258 | 1,087 | # coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'local-subdomain/version'
Gem::Specification.new do |spec|
spec.name = 'local-subdomain'
spec.version = LocalSubdomain::VERSION
spec.authors = ['Manuel van Rijn']
spec.email = ['manuel@manuelvanrijn.nl']
spec.summary = 'subdomain support in your development environment'
spec.description = "This gem helps out when your application depends on subdomain support and you don't want to modify you /etc/hosts file all the time for your development environment."
spec.homepage = 'https://github.com/manuelvanrijn/local-subdomain'
spec.license = 'MIT'
spec.files = `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) }
spec.bindir = 'exe'
spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
spec.require_paths = ['lib']
spec.add_development_dependency 'bundler', '~> 2.0'
spec.add_development_dependency 'rake', '~> 13.0'
end
| 43.48 | 190 | 0.672493 |
1a4057bbccb0977d6d412e270dc6c11ec8a1a854 | 2,121 | require File.expand_path('../../../spec_helper', __FILE__)
module Pod
describe Command::Package do
after do
Dir.glob("Pods").each { |dir| Pathname.new(dir).rmtree }
end
it "uses additional spec repos passed on the command line" do
Pod::Config.instance.sources_manager.stubs(:search).returns(nil)
nil::NilClass.any_instance.stubs(:install!)
Installer.expects(:new).with {
|sandbox, podfile| podfile.sources == ['foo', 'bar']
}
command = Command.parse(%w{ package spec/fixtures/KFData.podspec --spec-sources=foo,bar})
command.send(:install_pod, :osx, nil)
end
it "uses only the master repo if no spec repos were passed" do
Pod::Config.instance.sources_manager.stubs(:search).returns(nil)
nil::NilClass.any_instance.stubs(:install!)
Installer.expects(:new).with {
|sandbox, podfile| podfile.sources == ['https://github.com/CocoaPods/Specs.git']
}
command = Command.parse(%w{ package spec/fixtures/KFData.podspec })
command.send(:install_pod, :osx, nil)
end
it "creates separate static and dynamic target if dynamic is passed" do
source_dir = Dir.pwd
Pod::Config.instance.sources_manager.stubs(:search).returns(nil)
command = Command.parse(%w{ package spec/fixtures/NikeKit.podspec -dynamic})
t, w = command.send(:create_working_directory)
command.config.installation_root = Pathname.new(w)
command.config.sandbox_root = 'Pods'
static_sandbox = command.send(:build_static_sandbox, true)
static_installer = command.send(:install_pod, :ios, static_sandbox)
dynamic_sandbox = command.send(:build_dynamic_sandbox, static_sandbox, static_installer)
command.send(:install_dynamic_pod, dynamic_sandbox, static_sandbox, static_installer, Platform.ios)
static_sandbox_dir = Dir.new(Dir.pwd << "/Pods/Static")
dynamic_sandbox_dir = Dir.new(Dir.pwd << "/Pods/Dynamic")
static_sandbox_dir.to_s.should.not.be.empty
dynamic_sandbox_dir.to_s.should.not.be.empty
Dir.chdir(source_dir)
end
end
end
| 35.949153 | 105 | 0.690712 |
edfc50660dc90a37e1213b6fcb29dfa719daa712 | 417 | root = "/home/deploy/apps/octomaps/current"
working_directory root
pid"#{root}/tmp/pids/unicorn.pid"
stderr_path"#{root}/log/unicorn.log"
stdout_path"#{root}/log/unicorn.log"
listen"/tmp/unicorn.octomaps.sock"
worker_processes 2
timeout 75
# Force the bundler gemfile environment variable to
# reference the capistrano "current" symlink
before_exec do |_|
ENV["BUNDLE_GEMFILE"] = File.join(root, 'Gemfile')
end
| 26.0625 | 52 | 0.767386 |
4aec6a86df19f5c77e43a874b46a00971c5df732 | 3,622 | require "grit"
require 'cgi'
require "securerandom"
module Flowdock
class Git
class Commit
def initialize(external_thread_id, thread, tags, commit)
@commit = commit
@external_thread_id = external_thread_id
@thread = thread
@tags = tags
end
def to_hash
hash = {
external_thread_id: @external_thread_id,
event: "activity",
author: {
name: @commit[:author][:name],
email: @commit[:author][:email]
},
title: title,
thread: @thread,
body: body
}
hash[:tags] = @tags if @tags
encode(hash)
end
private
def encode(hash)
return hash unless "".respond_to? :encode
encode_as_utf8(hash)
end
# This only works on Ruby 1.9
def encode_as_utf8(obj)
if obj.is_a? Hash
obj.each_pair do |key, val|
encode_as_utf8(val)
end
elsif obj.is_a?(Array)
obj.each do |val|
encode_as_utf8(val)
end
elsif obj.is_a?(String) && obj.encoding != Encoding::UTF_8
if !obj.force_encoding("UTF-8").valid_encoding?
obj.force_encoding("ISO-8859-1").encode!(Encoding::UTF_8, :invalid => :replace, :undef => :replace)
end
end
end
def body
content = @commit[:message][first_line.size..-1]
content.strip! if content
"<pre>#{content}</pre>" unless content.empty?
end
def first_line
@first_line ||= (@commit[:message].split("\n")[0] || @commit[:message])
end
def title
commit_id = @commit[:id][0, 7]
if @commit[:url]
"<a href=\"#{@commit[:url]}\">#{commit_id}</a> #{message_title}"
else
"#{commit_id} #{message_title}"
end
end
def message_title
CGI.escape_html(first_line.strip)
end
end
# Class used to build Git payload
class Builder
def initialize(opts)
@repo = opts[:repo]
@ref = opts[:ref]
@before = opts[:before]
@after = opts[:after]
@opts = opts
end
def commits
@repo.commits_between(@before, @after).map do |commit|
{
url: if @opts[:commit_url] then @opts[:commit_url] % [commit.sha] end,
id: commit.sha,
message: commit.message,
author: {
name: commit.author.name,
email: commit.author.email
}
}
end
end
def ref_name
@ref.to_s.sub(/\Arefs\/(heads|tags)\//, '')
end
def to_hashes
commits.map do |commit|
Commit.new(external_thread_id, thread, @opts[:tags], commit).to_hash
end
end
private
def thread
@thread ||= {
title: thread_title,
external_url: @opts[:repo_url]
}
end
def permanent?
@permanent ||= @opts[:permanent_refs].select do |regex|
regex.match(@ref)
end.size > 0
end
def thread_title
action = if permanent?
"updated"
end
type = if @ref.match(%r(^refs/heads/))
"branch"
else
"tag"
end
[@opts[:repo_name], type, ref_name, action].compact.join(" ")
end
def external_thread_id
@external_thread_id ||=
if permanent?
SecureRandom.hex
else
@ref
end
end
end
end
end
| 23.986755 | 111 | 0.507454 |
2842a459a40150b622f0ae04b14d4d1d3264ec86 | 1,152 | module SessionsHelper
def log_in(user)
session[:user_id] = user.id
cookies.permanent.signed[:user_id] = user.id
end
def current_user
if (user_id = session[:user_id])
@current_user ||= User.find_by(id: user_id)
elsif (user_id = cookies.signed[:user_id])
user = User.find_by(id: user_id)
if user && user.authenticated?(cookies[:remember_token])
log_in user
@current_user = user
end
end
end
def remember(user)
user.remember
cookies.permanent.signed[:user_id] = user.id
cookies.permanent[:remember_token] = user.remember_token
end
def logged_in?
!current_user.nil?
end
def current_user?(user)
user == current_user
end
def forget(user)
user.forget
cookies.delete(:user_id)
cookies.delete(:remember_token)
end
def log_out
forget(current_user)
session.delete(:user_id)
@current_user = nil
end
def redirect_back_or(default)
redirect_to(session[:forwarding_url] || default)
session.delete(:forwarding_url)
end
def store_location
session[:forwarding_url] = request.original_url if request.get?
end
end
| 21.333333 | 67 | 0.682292 |
edc8fb7df54e1df6e8c52a037a095bf4458fe422 | 69 | # frozen_string_literal: true
module Falcon
VERSION = '1.0.0'
end
| 11.5 | 29 | 0.724638 |
213c2605ba762f461b50d0364c33e3bd1a0e9b17 | 1,265 | # This file is auto-generated from the current state of the database. Instead
# of editing this file, please use the migrations feature of Active Record to
# incrementally modify your database, and then regenerate this schema definition.
#
# Note that this schema.rb definition is the authoritative source for your
# database schema. If you need to create the application database on another
# system, you should be using db:schema:load, not running all the migrations
# from scratch. The latter is a flawed and unsustainable approach (the more migrations
# you'll amass, the slower it'll run and the greater likelihood for issues).
#
# It's strongly recommended that you check this file into your version control system.
ActiveRecord::Schema.define(version: 20180122190513) do
create_table "categories", force: :cascade do |t|
t.string "name"
end
create_table "task_categories", force: :cascade do |t|
t.integer "task_id"
t.integer "category_id"
end
create_table "tasks", force: :cascade do |t|
t.string "name"
t.string "summary"
t.integer "user_id"
t.index ["user_id"], name: "index_tasks_on_user_id"
end
create_table "users", force: :cascade do |t|
t.string "username"
t.string "password_digest"
end
end
| 34.189189 | 86 | 0.742292 |
f7a7aa7b82029475b60213af4d43525c79019ae9 | 1,659 | class Cabocha < Formula
desc "Yet Another Japanese Dependency Structure Analyzer"
homepage "https://taku910.github.io/cabocha/"
# Files are listed in https://drive.google.com/drive/folders/0B4y35FiV1wh7cGRCUUJHVTNJRnM
url "https://dl.bintray.com/homebrew/mirror/cabocha-0.69.tar.bz2"
mirror "https://mirrorservice.org/sites/ftp.netbsd.org/pub/pkgsrc/distfiles/cabocha-20160909/cabocha-0.69.tar.bz2"
sha256 "9db896d7f9d83fc3ae34908b788ae514ae19531eb89052e25f061232f6165992"
bottle do
sha256 "beafa5ccf84633bed67d405f22ac8e570d2dc2fe0e10fccf8c11076639c672ae" => :high_sierra
sha256 "27bd41bab80ab64fb32e5bc8b568864b874f0dec16817d38c37abd3c7582c694" => :sierra
sha256 "bf3ed6bc9333b43919264913c40a86997a7601a83abf6dcfa1dfe14745b3fc7c" => :el_capitan
sha256 "fe97decdca655899faffd6356bb8ddbb52d4949222690835374c3aeb9a65cdb2" => :yosemite
sha256 "794df46e362f3146b2bab17ba132978609954b0ba0a51ffa4d6d4e8845548764" => :mavericks
sha256 "b1aaf6623ac7332459c795ebd992ed92224b0d0b9e20fb57dd0313fbeea7647c" => :mountain_lion
end
depends_on "crf++"
depends_on "mecab"
depends_on "mecab-ipadic"
def install
ENV["LIBS"] = "-liconv"
inreplace "Makefile.in" do |s|
s.change_make_var! "CFLAGS", ENV.cflags
s.change_make_var! "CXXFLAGS", ENV.cflags
end
args = %W[
--disable-dependency-tracking
--prefix=#{prefix}
--with-charset=UTF8
--with-posset=IPA
]
system "./configure", *args
system "make", "install"
end
test do
result = `echo "CaboCha はフリーソフトウェアです。" | cabocha | md5`.chomp
assert_equal "a5b8293e6ebcb3246c54ecd66d6e18ee", result
end
end
| 36.065217 | 116 | 0.75648 |
d5266af89b51fd2437a6bdd23fcdfa05b04fe91f | 3,758 | describe GraylogAPI::System::Inputs, vcr: true do
include_context 'graylogapi'
context 'create input' do
subject(:response) do
options = { title: 'Test_create_input',
type: 'org.graylog.plugins.beats.BeatsInput',
global: true,
configuration: { bind_address: '0.0.0.0',
port: 5044,
recv_buffer_size: 1_048_576,
tls_client_auth: 'disabled' } }
req = graylogapi.system.inputs.create(options)
graylogapi.system.inputs.delete(req['id'])
req
end
it 'code 201' do
expect(response.code).to eq 201
end
it 'return id' do
expect(response.keys).to contain_exactly 'id'
end
end
context 'create input with type name insted of type' do
subject(:response) do
options = { title: 'Test_create_input',
type_name: 'Syslog UDP',
global: true,
configuration: { bind_address: '0.0.0.0',
port: 5014 } }
res = graylogapi.system.inputs.create(options)
graylogapi.system.inputs.delete(res['id'])
res
end
it 'code 201' do
expect(response.code).to eq 201
end
it 'return id' do
expect(response.keys).to contain_exactly 'id'
end
end
context 'update input' do
subject(:response) do
options = { title: 'Input by gem123',
type: 'org.graylog.plugins.beats.BeatsInput',
global: true,
configuration: { bind_address: '0.0.0.0',
port: 5044 } }
input = graylogapi.system.inputs.create(options)
req = graylogapi.system.inputs.update(input['id'], options)
graylogapi.system.inputs.delete(input['id'])
req
end
it 'code 201' do
expect(response.code).to eq 201
end
it 'return id' do
expect(response.keys).to contain_exactly 'id'
end
end
context 'update input with type name instead of type' do
subject(:response) do
options = { title: 'Update_input',
type_name: 'Beats',
global: true,
configuration: { bind_address: '0.0.0.0',
port: 5044 } }
input = graylogapi.system.inputs.create(options)
res = graylogapi.system.inputs.update(input['id'], options)
graylogapi.system.inputs.delete(input['id'])
res
end
it 'code 201' do
expect(response.code).to eq 201
end
it 'return id' do
expect(response.keys).to contain_exactly 'id'
end
end
context 'get all inputs' do
subject(:response) { graylogapi.system.inputs.all }
it 'code 200' do
expect(response.code).to eq 200
end
it 'contain count of inputs' do
expect(response.keys).to include 'total'
end
it 'contain array of inputs' do
expect(response.keys).to include 'inputs'
end
end
context 'get by id' do
subject(:response) do
options = { title: 'Input by gem123',
type: 'org.graylog.plugins.beats.BeatsInput',
global: true,
configuration: { bind_address: '0.0.0.0',
port: 5044 } }
input = graylogapi.system.inputs.create(options)
req = graylogapi.system.inputs.by_id(input['id'])
graylogapi.system.inputs.delete(input['id'])
req
end
it 'code 200' do
expect(response.code).to eq 200
end
it 'contain id' do
expect(response.keys).to include 'id'
end
it 'contain title' do
expect(response.keys).to include 'title'
end
end
end
| 27.632353 | 66 | 0.562001 |
b9b5a04755aff2700710149c050044e03a71d41a | 808 | class Prime::Eth2Staking::BaseController < Prime::ApplicationController
before_action :set_metadata
before_action :require_eth_staking
private
def set_metadata
@page_title = 'Ethereum Staking Management'
end
def anjin_client
Prime::Anjin::Client.current
end
def require_eth_staking
# Primary feature flag check on customer level
unless current_user.prime_eth_staking_enabled
flash[:error] = 'Sorry, Ethereum staking management is not available on your account.'
return redirect_to prime_root_path
end
# In case if customer ID gets deleted
if current_user.prime_eth_staking_customer_id.blank?
flash[:error] = 'Sorry, Ethereum staking management is temporarily unavailable on your account.'
redirect_to prime_root_path
end
end
end
| 27.862069 | 102 | 0.758663 |
e99ef1984288b11703a390d89bc2f91ead43b089 | 2,893 | require 'action_view/helpers/javascript_helper'
ActionView::Helpers::JavaScriptHelper.module_eval do
include ActionView::Helpers::PrototypeHelper
# Returns a button with the given +name+ text that'll trigger a JavaScript +function+ using the
# onclick handler.
#
# The first argument +name+ is used as the button's value or display text.
#
# The next arguments are optional and may include the javascript function definition and a hash of html_options.
#
# The +function+ argument can be omitted in favor of an +update_page+
# block, which evaluates to a string when the template is rendered
# (instead of making an Ajax request first).
#
# The +html_options+ will accept a hash of html attributes for the link tag. Some examples are :class => "nav_button", :id => "articles_nav_button"
#
# Note: if you choose to specify the javascript function in a block, but would like to pass html_options, set the +function+ parameter to nil
#
# Examples:
# button_to_function "Greeting", "alert('Hello world!')"
# button_to_function "Delete", "if (confirm('Really?')) do_delete()"
# button_to_function "Details" do |page|
# page[:details].visual_effect :toggle_slide
# end
# button_to_function "Details", :class => "details_button" do |page|
# page[:details].visual_effect :toggle_slide
# end
def button_to_function(name, *args, &block)
html_options = args.extract_options!.symbolize_keys
function = block_given? ? update_page(&block) : args[0] || ''
onclick = "#{"#{html_options[:onclick]}; " if html_options[:onclick]}#{function};"
tag(:input, html_options.merge(:type => 'button', :value => name, :onclick => escape_once(onclick)), false, false)
end
# link_to_function("Show me more", nil, :id => "more_link") do |page|
# page[:details].visual_effect :toggle_blind
# page[:more_link].replace_html "Show me less"
# end
# Produces:
# <a href="#" id="more_link" onclick="try {
# $("details").visualEffect("toggle_blind");
# $("more_link").update("Show me less");
# }
# catch (e) {
# alert('RJS error:\n\n' + e.toString());
# alert('$(\"details\").visualEffect(\"toggle_blind\");
# \n$(\"more_link\").update(\"Show me less\");');
# throw e
# };
# return false;">Show me more</a>
#
def link_to_function(name, *args, &block)
html_options = args.extract_options!.symbolize_keys
function = block_given? ? update_page(&block) : args[0] || ''
onclick = "#{"#{html_options[:onclick]}; " if html_options[:onclick]}#{function}; return false;"
href = html_options[:href] || '#'
content_tag(:a, name, html_options.merge(:href => href, :onclick => escape_once(onclick)), false)
end
end
| 43.833333 | 149 | 0.660214 |
e99e67c8c02ec7ab7f3bbc5ed03a13f92a805020 | 287 | # frozen_string_literal: true
require 'rails_helper'
require 'spree/testing_support/factories/store_factory'
RSpec.describe 'store factory' do
let(:factory_class) { Spree::Store }
describe 'store' do
let(:factory) { :store }
it_behaves_like 'a working factory'
end
end
| 19.133333 | 55 | 0.738676 |
28d1a88ffcf6438bfaa70f71ad7a16ecb06576e8 | 4,819 | require "cheffish"
require "chef/version"
require "chef_zero/server"
require "chef/chef_fs/chef_fs_data_store"
require "chef/chef_fs/config"
require "cheffish/chef_run_data"
require "cheffish/chef_run_listener"
require "chef/client"
require "chef/config"
require "chef_zero/version"
require "cheffish/merged_config"
require "chef/resource/chef_acl"
require "chef/resource/chef_client"
require "chef/resource/chef_container"
require "chef/resource/chef_data_bag"
require "chef/resource/chef_data_bag_item"
require "chef/resource/chef_environment"
require "chef/resource/chef_group"
require "chef/resource/chef_mirror"
require "chef/resource/chef_node"
require "chef/resource/chef_organization"
require "chef/resource/chef_role"
require "chef/resource/chef_user"
require "chef/resource/private_key"
require "chef/resource/public_key"
class Chef
module DSL
module Recipe
def with_chef_data_bag(name)
run_context.cheffish.with_data_bag(name, &block)
end
def with_chef_environment(name, &block)
run_context.cheffish.with_environment(name, &block)
end
def with_chef_data_bag_item_encryption(encryption_options, &block)
run_context.cheffish.with_data_bag_item_encryption(encryption_options, &block)
end
def with_chef_server(server_url, options = {}, &block)
run_context.cheffish.with_chef_server({ :chef_server_url => server_url, :options => options }, &block)
end
def with_chef_local_server(options, &block)
options[:host] ||= "127.0.0.1"
options[:log_level] ||= Chef::Log.level
options[:port] ||= ChefZero::VERSION.to_f >= 2.2 ? 8901.upto(9900) : 8901
# Create the data store chef-zero will use
options[:data_store] ||= begin
if !options[:chef_repo_path]
raise "chef_repo_path must be specified to with_chef_local_server"
end
# Ensure all paths are given
%w{acl client cookbook container data_bag environment group node role}.each do |type|
# Set the options as symbol keys and then copy to string keys
string_key = "#{type}_path"
symbol_key = "#{type}_path".to_sym
options[symbol_key] ||= begin
if options[:chef_repo_path].kind_of?(String)
Chef::Util::PathHelper.join(options[:chef_repo_path], "#{type}s")
else
options[:chef_repo_path].map { |path| Chef::Util::PathHelper.join(path, "#{type}s") }
end
end
# Copy over to string keys for things that use string keys (ChefFS)...
# TODO: Fix ChefFS to take symbols or use something that is insensitive to the difference
options[string_key] = options[symbol_key]
end
chef_fs = Chef::ChefFS::Config.new(options).local_fs
chef_fs.write_pretty_json = true
Chef::ChefFS::ChefFSDataStore.new(chef_fs)
end
# Start the chef-zero server
Chef::Log.info("Starting chef-zero on port #{options[:port]} with repository at #{options[:data_store].chef_fs.fs_description}")
chef_zero_server = ChefZero::Server.new(options)
chef_zero_server.start_background
run_context.cheffish.local_servers << chef_zero_server
with_chef_server(chef_zero_server.url, &block)
end
def get_private_key(name)
Cheffish.get_private_key(name, run_context.config)
end
end
end
class Config
default(:profile) { ENV["CHEF_PROFILE"] || "default" }
configurable(:private_keys)
default(:private_key_paths) { [ Chef::Util::PathHelper.join(config_dir, "keys"), Chef::Util::PathHelper.join(user_home, ".ssh") ] }
default(:private_key_write_path) { private_key_paths.first }
end
class RunContext
def cheffish
node.run_state[:cheffish] ||= begin
run_data = Cheffish::ChefRunData.new(config)
events.register(Cheffish::ChefRunListener.new(node))
run_data
end
end
def config
node.run_state[:chef_config] ||= Cheffish.profiled_config(Chef::Config)
end
end
Chef::Client.when_run_starts do |run_status|
# Pulling on cheffish_run_data makes it initialize right now
run_status.node.run_state[:chef_config] = config = Cheffish.profiled_config(Chef::Config)
run_status.node.run_state[:cheffish] = run_data = Cheffish::ChefRunData.new(config)
run_status.events.register(Cheffish::ChefRunListener.new(run_status.node))
end
end
# Chef 12 moved Chef::Config.path_join to PathHelper.join
if Chef::VERSION.to_i >= 12
require "chef/util/path_helper"
else
require "chef/config"
class Chef
class Util
class PathHelper
def self.join(*args)
Chef::Config.path_join(*args)
end
end
end
end
end
| 33.699301 | 136 | 0.687695 |
26aefa8864474dd8728bc4c03b6bb0604d9570ec | 37 | node.default['nginx']['port'] = 8080
| 18.5 | 36 | 0.648649 |
26353e32fabcd6594255a8f74f59e9e8236d3cf8 | 3,294 | # frozen_string_literal: true
require "cases/helper"
require "active_support/core_ext/numeric/time"
require "models/topic"
require "models/person"
class ExclusionValidationTest < ActiveModel::TestCase
def teardown
Topic.clear_validators!
end
def test_validates_exclusion_of
Topic.validates_exclusion_of(:title, in: %w( abe monkey ))
assert_predicate Topic.new("title" => "something", "content" => "abc"), :valid?
assert_predicate Topic.new("title" => "monkey", "content" => "abc"), :invalid?
end
def test_validates_exclusion_of_with_formatted_message
Topic.validates_exclusion_of(:title, in: %w( abe monkey ), message: "option %{value} is restricted")
assert Topic.new("title" => "something", "content" => "abc")
t = Topic.new("title" => "monkey")
assert_predicate t, :invalid?
assert_predicate t.errors[:title], :any?
assert_equal ["option monkey is restricted"], t.errors[:title]
end
def test_validates_exclusion_of_with_within_option
Topic.validates_exclusion_of(:title, within: %w( abe monkey ))
assert Topic.new("title" => "something", "content" => "abc")
t = Topic.new("title" => "monkey")
assert_predicate t, :invalid?
assert_predicate t.errors[:title], :any?
end
def test_validates_exclusion_of_for_ruby_class
Person.validates_exclusion_of :karma, in: %w( abe monkey )
p = Person.new
p.karma = "abe"
assert_predicate p, :invalid?
assert_equal ["is reserved"], p.errors[:karma]
p.karma = "Lifo"
assert_predicate p, :valid?
ensure
Person.clear_validators!
end
def test_validates_exclusion_of_with_lambda
Topic.validates_exclusion_of :title, in: lambda { |topic| topic.author_name == "sikachu" ? %w( monkey elephant ) : %w( abe wasabi ) }
t = Topic.new
t.title = "elephant"
t.author_name = "sikachu"
assert_predicate t, :invalid?
t.title = "wasabi"
assert_predicate t, :valid?
end
def test_validates_exclusion_of_with_lambda_without_arguments
Topic.validates_exclusion_of :title, in: lambda { %w( monkey elephant ) }
t = Topic.new
t.title = "monkey"
assert_predicate t, :invalid?
t.title = "wasabi"
assert_predicate t, :valid?
end
def test_validates_exclusion_of_with_range
Topic.validates_exclusion_of :content, in: ("a".."g")
assert_predicate Topic.new(content: "g"), :invalid?
assert_predicate Topic.new(content: "h"), :valid?
end
def test_validates_exclusion_of_with_time_range
Topic.validates_exclusion_of :created_at, in: 6.days.ago..2.days.ago
assert_predicate Topic.new(created_at: 5.days.ago), :invalid?
assert_predicate Topic.new(created_at: 3.days.ago), :invalid?
assert_predicate Topic.new(created_at: 7.days.ago), :valid?
assert_predicate Topic.new(created_at: 1.day.ago), :valid?
end
def test_validates_inclusion_of_with_symbol
Person.validates_exclusion_of :karma, in: :reserved_karmas
p = Person.new
p.karma = "abe"
def p.reserved_karmas
%w(abe)
end
assert_predicate p, :invalid?
assert_equal ["is reserved"], p.errors[:karma]
p = Person.new
p.karma = "abe"
def p.reserved_karmas
%w()
end
assert_predicate p, :valid?
ensure
Person.clear_validators!
end
end
| 27.22314 | 137 | 0.697936 |
080656aff8c1dc3787e964e26bd023353dffff74 | 588 | require 'facets/matchdata/matchset'
require 'test/unit'
class Test_MatchData_Matchset < Test::Unit::TestCase
def test_matchtree_01
md = /(bb)(cc(dd))(ee)/.match "XXaabbccddeeffXX"
assert_equal( [["bb"], ["cc", ["dd"]], ["ee"]] , md.matchtree )
end
def test_matchtree_02
md = /(bb)c(c(dd))(ee)/.match "XXaabbccddeeffXX"
assert_equal( [["bb"], "c", ["c", ["dd"]], ["ee"]] , md.matchtree )
end
def test_matchset
md = /(bb)(cc(dd))(ee)/.match "XXaabbccddeeffXX"
assert_equal( ["XXaa", [["bb"], ["cc", ["dd"]], ["ee"]], "ffXX"] , md.matchset )
end
end
| 26.727273 | 84 | 0.595238 |
0874cd902ffd96a3b4344987c6e28d8a9e9e0691 | 1,584 | # Copyright (c) 2018 Corey Bonnell
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
require 'digest'
module SctCheck
class Utils
def self.log_cert_info message, log_level, cert
cert_fingerprint = Digest::SHA1.hexdigest(cert.to_der).upcase.scan(/../).join(':')
serial = cert.serial.to_s(16).scan(/../).join(':')
$logger.add log_level, "#{message}, " +
"subject: \"#{cert.subject.to_s}\", " +
"serial: #{serial}, " +
"fingerprint: #{cert_fingerprint}"
end
end
end
| 42.810811 | 94 | 0.702652 |
ac2869f23ab7c48ced98971343dcb699f94bd4a9 | 52 | class Offdays < ActiveRecord::Base
unloadable
end
| 13 | 34 | 0.788462 |
e2e462d75f701c232ad15c06e6c80e95f0587b24 | 102 | require 'rspec/rails'
RSpec.configure do |config|
config.before do
Rails.cache.clear
end
end
| 12.75 | 27 | 0.72549 |
1ddee55015d39f96a3ef2cdef4f94fdacf504d61 | 863 | # frozen_string_literal: true
# Be sure to restart your server when you modify this file.
# Version of your assets, change this if you want to expire all your assets.
Rails.application.config.assets.version = '1.1'
# Activeadmin assets
Rails.application.config.assets.precompile += %w(active_admin/active_admin_globalize.css)
Rails.application.config.assets.precompile += %w(active_admin/active_admin_globalize.js)
# Mapbox assets
Rails.application.config.assets.precompile += %w(icons-*.png)
# Email / Newsletter / Maintenance assets
Rails.application.config.assets.precompile += %w(email.css newsletter.css maintenance.css noscript.css)
# ActiveAdmin Addons (paperclip attachment)
Rails.application.config.assets.precompile += %w(fileicons/*.png)
# DelayedJob (web interface)
Rails.application.config.assets.precompile += %w(delayed/web/application.css)
| 37.521739 | 103 | 0.791425 |
3907dd7d607399fccafb11cea52679c3c99c085f | 363 | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe Types::Dast::SiteProfileAuthInputType do
specify { expect(described_class.graphql_name).to eq('DastSiteProfileAuthInput') }
it 'has the correct arguments' do
expect(described_class.arguments.keys).to match_array(%w[enabled url usernameField passwordField username password])
end
end
| 30.25 | 120 | 0.801653 |
1af8d7458d935dc4aaad85b75604d6dae4fea29d | 2,411 | ##
# This file is part of the Metasploit Framework and may be subject to
# redistribution and commercial restrictions. Please see the Metasploit
# web site for more information on licensing and terms of use.
# http://metasploit.com/
##
require 'msf/core'
require 'rex/proto/ipmi'
class Metasploit3 < Msf::Auxiliary
include Msf::Auxiliary::Report
include Msf::Auxiliary::UDPScanner
def initialize
super(
'Name' => 'IPMI 2.0 RAKP Cipher Zero Authentication Bypass Scanner',
'Description' => %q|
This module identifies IPMI 2.0 compatible systems that are vulnerable
to an authentication bypass vulnerability through the use of cipher
zero.
|,
'Author' => [ 'Dan Farmer <zen[at]fish2.com>', 'hdm' ],
'License' => MSF_LICENSE,
'References' =>
[
['URL', 'http://fish2.com/ipmi/cipherzero.html'],
['OSVDB', '93038'],
['OSVDB', '93039'],
['OSVDB', '93040'],
],
'DisclosureDate' => 'Jun 20 2013'
)
register_options(
[
Opt::RPORT(623)
], self.class)
end
def scanner_prescan(batch)
print_status("Sending IPMI requests to #{batch[0]}->#{batch[-1]} (#{batch.length} hosts)")
@res = {}
end
def scan_host(ip)
console_session_id = Rex::Text.rand_text(4)
scanner_send(
Rex::Proto::IPMI::Utils.create_ipmi_session_open_cipher_zero_request(console_session_id),
ip, datastore['RPORT']
)
end
def scanner_process(data, shost, sport)
info = Rex::Proto::IPMI::Open_Session_Reply.new(data) rescue nil
return if not info
return if not info.session_payload_type == Rex::Proto::IPMI::PAYLOAD_RMCPPLUSOPEN_REP
# Ignore duplicate replies
return if @res[shost]
@res[shost] ||= info
if info.error_code == 0
print_good("#{shost}:#{sport} - IPMI - VULNERABLE: Accepted a session open request for cipher zero")
report_vuln(
:host => shost,
:port => datastore['RPORT'].to_i,
:proto => 'udp',
:sname => 'ipmi',
:name => 'IPMI 2.0 RAKP Cipher Zero Authentication Bypass',
:info => "Accepted a session open request for cipher zero",
:refs => self.references
)
else
vprint_status("#{shost}:#{sport} - IPMI - NOT VULNERABLE: Rejected cipher zero with error code #{info.error_code}")
end
end
end
| 28.702381 | 121 | 0.624222 |
79bfbce5aaa73b6243af54c9eb77770e8cd32284 | 4,931 | require 'spec_helper'
RSpec.describe MeasurePresenter do
describe '#geo_class' do
context 'when geographical area is a country group' do
subject { MeasurePresenter.new(measure) }
let(:children_ga) { [attributes_for(:geographical_area).stringify_keys, attributes_for(:geographical_area).stringify_keys] }
let(:geographical_area) { attributes_for(:geographical_area, geographical_area_id: nil, children_geographical_areas: children_ga).stringify_keys }
let(:measure) { Measure.new(attributes_for(:measure, geographical_area: geographical_area).stringify_keys) }
it 'returns list of contained children geographical area ids' do
expect(subject.geo_class).to match(/#{children_ga.first[:geographical_area_id]}/)
expect(subject.geo_class).to match(/#{children_ga.last[:geographical_area_id]}/)
end
end
context 'when geographical area is a country' do
subject { MeasurePresenter.new(measure) }
let(:geographical_area) { attributes_for(:geographical_area).stringify_keys }
let(:measure) { Measure.new(attributes_for(:measure, geographical_area: geographical_area).stringify_keys) }
it 'returns geographical area id of geographical area' do
expect(subject.geo_class).to match(/#{geographical_area[:geographical_area_id]}/)
end
end
end
describe '#has_children_geographical_areas?' do
let(:children_ga) { [attributes_for(:geographical_area).stringify_keys, attributes_for(:geographical_area).stringify_keys] }
let(:geographical_area) { attributes_for(:geographical_area, geographical_area_id: nil, children_geographical_areas: children_ga).stringify_keys }
let(:measure1) { MeasurePresenter.new(Measure.new(attributes_for(:measure, geographical_area: geographical_area).stringify_keys)) }
let(:measure2) { MeasurePresenter.new(Measure.new(attributes_for(:measure, geographical_area: attributes_for(:geographical_area).stringify_keys).stringify_keys)) }
it 'returns true if measures geographical area contains any children geographical area' do
expect(measure1.has_children_geographical_areas?).to be true
end
it 'returns false if measures geographical area has no children geographical area' do
expect(measure2.has_children_geographical_areas?).to be false
end
end
describe '#children_geographical_areas' do
let(:children_ga) { [attributes_for(:geographical_area).stringify_keys, attributes_for(:geographical_area).stringify_keys] }
let(:geographical_area) { attributes_for(:geographical_area, geographical_area_id: nil, children_geographical_areas: children_ga).stringify_keys }
let(:measure1) { MeasurePresenter.new(Measure.new(attributes_for(:measure, geographical_area: geographical_area))) }
it 'returns measure geographical area children geographical areas' do
expect(measure1.children_geographical_areas).to have_attribute_superset_of children_ga.first
expect(measure1.children_geographical_areas).to have_attribute_superset_of children_ga.last
end
end
describe '#has_measure_conditions?' do
let(:measure1) { MeasurePresenter.new(Measure.new(attributes_for(:measure, :with_conditions).stringify_keys)) }
let(:measure2) { MeasurePresenter.new(Measure.new(attributes_for(:measure).stringify_keys)) }
it 'returns true if measure has measure conditions' do
expect(measure1.has_measure_conditions?).to be true
end
it 'returns false if measure has no measure conditions' do
expect(measure2.has_measure_conditions?).to be false
end
end
describe '#has_additional_code?' do
let(:measure1) { MeasurePresenter.new(Measure.new(attributes_for(:measure, :with_additional_code).stringify_keys)) }
let(:measure2) { MeasurePresenter.new(Measure.new(attributes_for(:measure).stringify_keys)) }
it 'returns true if measure has additional code' do
expect(measure1.has_additional_code?).to be true
end
it 'returns false if measure has no additional code' do
expect(measure2.has_additional_code?).to be false
end
end
describe '#has_references?' do
let(:measure1) { MeasurePresenter.new(Measure.new(attributes_for(:measure, :with_conditions).stringify_keys)) }
let(:measure2) { MeasurePresenter.new(Measure.new(attributes_for(:measure, :with_footnotes).stringify_keys)) }
let(:measure3) { MeasurePresenter.new(Measure.new(attributes_for(:measure).stringify_keys)) }
it 'returns true if measure has conditions' do
expect(measure1.has_references?).to be true
end
it 'returns true if measure has footnotes' do
expect(measure2.has_references?).to be true
end
it 'returns false if measure has no footnotes or conditions' do
expect(measure3.has_references?).to be false
end
end
end
| 48.821782 | 176 | 0.743054 |
91278f9a2ab02a1add67d296ad9fd045683b386c | 685 | # == Schema Information
#
# Table name: services
#
# id :integer not null, primary key
# created_at :datetime not null
# updated_at :datetime not null
# type :string not null
# uuid :string not null
# name :string not null
# health :integer default(0), not null
# status :integer
# status_msg :string
#
# Indexes
#
# index_services_on_type (type)
# index_services_on_uuid (uuid)
#
FactoryGirl.define do
factory :service do
type 'Service'
sequence :name do |n|
"Service #{n}"
end
uuid SecureRandom.uuid
health :ok
status :pending
end
end
| 20.147059 | 53 | 0.578102 |
917dc2e20a33c23200ab1562402e782bbcf08009 | 868 | require 'equalizer'
require 'adamantium'
require_relative 'iban/extended_data'
require_relative 'iban/country_codes'
require_relative 'iban/validator'
class Ibanizator
class Iban
attr_reader :iban_string
alias_method :to_s, :iban_string
include Equalizer.new(:iban_string)
include Adamantium
def initialize(an_iban)
@iban_string = sanitize(an_iban)
end
def self.from_string(a_string)
new(a_string)
end
def country_code
cc = iban_string[0..1].to_sym
COUNTRY_CODES.keys.include?(cc) ? cc : :unknown
end
memoize :country_code
def extended_data
ExtendedData::DE.new(self) if country_code == :DE
end
memoize :extended_data
def valid?
Validator.new(self).validate
end
private
def sanitize(input)
input.to_s.gsub(/\s+/, '').upcase
end
end
end
| 18.869565 | 55 | 0.68318 |
79f329a0d368a0174a3e736cf953d9981195c0b7 | 412 | # frozen_string_literal: true
require "rails_helper"
RSpec.describe "clients/new", type: :view do
before(:each) do
assign(:client, build(:client))
end
it "renders new client form" do
render
assert_select "form[action=?][method=?]", clients_path, "post" do
assert_select "input[name=?]", "client[first_name]"
assert_select "input[name=?]", "client[last_name]"
end
end
end
| 20.6 | 69 | 0.669903 |
ff5c5145fde076dedcc7899fb8313e952e6c7cfe | 166 | class AddColumnsToItems < ActiveRecord::Migration[5.1]
def change
add_column :items, :image_url, :string
add_column :items, :staff_message, :text
end
end
| 23.714286 | 54 | 0.73494 |
bbeda3d6cc413f4380eb3ec8b350d1a583b9fa4f | 2,127 | require "myfinance/request"
require "myfinance/response"
module Myfinance
class Client
attr_reader :http
def initialize(token, account_id = nil)
@http = Http.new(token, account_id)
end
def authenticated?
http.get("/accounts") { |response| response.code == 200 }
rescue RequestError => e
raise e unless [401, 403].include?(e.code)
false
end
def entities
Myfinance::Resources::Entity.new(http)
end
def financial_transactions
Myfinance::Resources::FinancialTransaction.new(http)
end
def payable_accounts
Myfinance::Resources::PayableAccount.new(http)
end
def receivable_accounts
Myfinance::Resources::ReceivableAccount.new(http)
end
def attachments
Myfinance::Resources::Attachment.new(http)
end
def classification_centers
Myfinance::Resources::ClassificationCenter.new(http)
end
def categories
Myfinance::Resources::Category.new(http)
end
def accounts
Myfinance::Resources::Account.new(http)
end
def deposit_accounts
Myfinance::Resources::DepositAccount.new(http)
end
def people
Myfinance::Resources::Person.new(http)
end
def webhooks
Myfinance::Resources::Webhook.new(http)
end
def taxes
Myfinance::Resources::Tax.new(http)
end
def credit_cards
Myfinance::Resources::CreditCard.new(http)
end
def credit_card_transactions
Myfinance::Resources::CreditCardTransaction.new(http)
end
def reconciles
Myfinance::Resources::Reconcile.new(http)
end
def bank_statements
Myfinance::Resources::BankStatement.new(http)
end
def sales
Myfinance::Resources::Sale.new(http)
end
def sale_accounts
Myfinance::Resources::SaleAccount.new(http)
end
def sale_rules
Myfinance::Resources::SaleRule.new(http)
end
def custom_classifiers
Myfinance::Resources::CustomClassifier.new(http)
end
def custom_classifier_values
Myfinance::Resources::CustomClassifierValue.new(http)
end
end
end
| 20.451923 | 63 | 0.67842 |
bb2fecf25d18f989d135ed9334f40292c8dbca35 | 3,594 | module Helpers
TEST_DIR = Pathname.new(__FILE__).parent + '..'
TYPES = {
:ec2 => :ec2
}
def self.included(obj)
obj.instance_eval { attr_accessor :valid_params }
end
# self is available at the describe level
def restricted_params(key, params, opts={}, invalid='invalid')
params.each do |param|
#let(:param) {param}
#let(:key) {key}
with(valid_params_with({key => param}))[key].should == param
end
lambda {with(valid_params_with({key => invalid}))}.should raise_error
end
# test that a list of attributes are required
def should_require(*keys)
keys.each do |k|
lambda { with(valid_params_without(k)) }.should raise_error Puppet::Error
end
end
# tests that an attribute should accept a value
def should_accept(attr, value)
k=attr.to_sym
with(valid_params_with({k => value}))[k].should == value
end
# tests that an attribute should not accept a value
def should_not_accept(attr, value)
k=attr.to_sym
lambda {with(valid_params_with({k => value}))}.should raise_error Puppet::Error
end
# tests that an attribute accepts an array
# - single element array, multiple element array
# - string is converted into an array
def should_accept_array(attr, value=['one', 'two'])
should_accept(attr, value)
should_accept(attr, value.first.to_a )
with(valid_params_with({attr => value.first}))[attr].should == value.first.to_a
end
# test that an attribute defaults to a value
def should_default_to(attr, defaultto)
with(valid_params_without(attr.to_sym))[:comment].should == defaultto
end
# Creates a new resource of +type+
def with(opts = {}, &block)
resource = @type.new(opts)
block ? (yield resource) : resource
end
# what is the difference?
# Returns a lambda creating a resource (ready for use with +should+)
def specifying(opts = {}, &block)
specification = lambda { with(opts) }
block ? (yield specification) : specification
end
# Sets up an expection that a resource for +type+ is not created
def should_not_create(type)
raise "Invalid type #{type}" unless TYPES[type]
Puppet::Type.type(TYPES[type]).expects(:new).never
end
# Sets up an expection that a resource for +type+ is created
def should_create(type)
raise "Invalid type #{type}" unless TYPES[type]
Puppet::Type.type(TYPES[type]).expects(:new).with { |args| yield(args) }
end
# Return the +@valid_params+ without one or more keys
# Note: Useful since resource types don't like it when +nil+ is
# passed as a parameter value
def valid_params_without(*keys)
valid_params.reject { |k, v| keys.include?(k) }
end
# yeah! I added this one!
def valid_params_with(opts = {})
opts.each { |k, v| valid_params[k] = v}
valid_params
end
# Stub the default provider to get around confines for testing
def stub_default_provider!(name)
unless defined?(@type)
raise ArgumentError, "@type must be set"
end
provider = @type.provider(name.to_sym)
@type.stubs(:defaultprovider => provider)
end
def fixture(name, ext = '.txt')
(TEST_DIR + 'fixtures' + "#{name}#{ext}").read
end
end
#Spec::Example::ExampleGroupFactory.register(:provider, ProviderExampleGroup)
#
# Outside wrapper to lookup a provider and start the spec using ProviderExampleGroup
#def describe_provider(type_name, provider_name, options = {}, &block)
# provider_class = Puppet::Type.type(type_name).provider(provider_name)
# describe(provider_class, options.merge(:type => :provider), &block)
#end
| 31.80531 | 84 | 0.686978 |
1aba3086b424f76f3a7271010ffd8471cc30ed14 | 4,407 | require 'spec_helper'
# Tests use of the Generator when used like so:
#
# @gen = IniParse::Generator.new
# @gen.comment('My very own comment')
# @gen.section('my_section')
# @gen.option('my_option', 'my value')
# ...
#
# Or
#
# IniParse::Generator.gen do |doc|
# doc.comment('My very own comment')
# doc.section('my_section')
# doc.option('my_option', 'my value')
# end
#
describe 'When generating a document using Generator without section blocks,' do
before(:each) { @gen = IniParse::Generator.new }
# --
# ==========================================================================
# SECTION LINES
# ==========================================================================
# ++
describe 'adding a section' do
it 'should add a Section to the document' do
@gen.section("a section")
expect(@gen.document).to have_section("a section")
end
it 'should change the Generator context to the section' do
@gen.section("a section")
expect(@gen.context).to eq(@gen.document['a section'])
end
it 'should pass extra options to the Section instance' do
@gen.section("a section", :indent => ' ')
expect(@gen.document["a section"].to_ini).to match(/\A /)
end
end
# --
# ==========================================================================
# OPTION LINES
# ==========================================================================
# ++
describe 'adding a option' do
it 'should pass extra options to the Option instance' do
@gen.section("a section")
@gen.option("my option", "a value", :indent => ' ')
expect(@gen.document["a section"].option("my option").to_ini).to match(/^ /)
end
describe 'when the context is a Document' do
it "should add the option to an __anonymous__ section" do
@gen.option("key", "value")
expect(@gen.document['__anonymous__']['key']).to eql('value')
end
end
describe 'when the context is a Section' do
it 'should add the option to the section' do
@gen.section("a section")
@gen.option("my option", "a value")
expect(@gen.document["a section"]).to have_option("my option")
expect(@gen.document["a section"]["my option"]).to eq("a value")
end
end
end
# --
# ==========================================================================
# COMMENT LINES
# ==========================================================================
# ++
describe 'adding a comment' do
it 'should pass extra options to the Option instance' do
@gen.comment("My comment", :indent => ' ')
expect(@gen.document.lines.to_a.first.to_ini).to match(/^ /)
end
it 'should ignore any extra :comment option' do
@gen.comment("My comment", :comment => 'Ignored')
comment_ini = @gen.document.lines.to_a.first.to_ini
expect(comment_ini).to match(/My comment/)
expect(comment_ini).not_to match(/Ignored/)
end
describe 'when the context is a Document' do
it 'should add a comment to the document' do
@gen.comment('My comment')
comment = @gen.document.lines.to_a.first
expect(comment).to be_kind_of(IniParse::Lines::Comment)
expect(comment.to_ini).to match(/; My comment/)
end
end
describe 'when the context is a Section' do
it 'should add a comment to the section' do
@gen.section('a section')
@gen.comment('My comment')
comment = @gen.document['a section'].lines.to_a.first
expect(comment).to be_kind_of(IniParse::Lines::Comment)
expect(comment.to_ini).to match(/My comment/)
end
end
end
# --
# ==========================================================================
# BLANK LINES
# ==========================================================================
# ++
describe 'adding a blank line' do
it 'should add a blank line to the document when it is the context' do
@gen.blank
comment = @gen.document.lines.to_a.first
expect(comment).to be_kind_of(IniParse::Lines::Blank)
end
it 'should add a blank line to the section when it is the context' do
@gen.section('a section')
@gen.blank
comment = @gen.document['a section'].lines.to_a.first
expect(comment).to be_kind_of(IniParse::Lines::Blank)
end
end
end
| 32.167883 | 85 | 0.535058 |
e27adb9e37c793e5b7234547eb0a83ff46ac0e82 | 285 | # frozen_string_literal: true
module LanguageConcepts
class ConceptSerializer < ::ApplicationSerializer
type 'concepts'
attributes(
:name,
:type
)
#has_one :representation do
# data do
# @object.representation
# end
#end
end
end
| 15 | 51 | 0.635088 |
Subsets and Splits