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
|
---|---|---|---|---|---|
1dd9b38b7e0898325bc8e0c4f7506ce788b580e0 | 545 | cask 'cyberduck' do
version '6.9.4.30164'
sha256 '061debe0eb69146764abc06915dbc1f45f7f939d15278f8cc23f3519ef7f3854'
url "https://update.cyberduck.io/Cyberduck-#{version}.zip"
appcast 'https://version.cyberduck.io/changelog.rss'
name 'Cyberduck'
homepage 'https://cyberduck.io/'
auto_updates true
app 'Cyberduck.app'
zap trash: [
'~/Library/Application Support/Cyberduck',
'~/Library/Caches/ch.sudo.cyberduck',
'~/Library/Preferences/ch.sudo.cyberduck.plist',
]
end
| 27.25 | 75 | 0.669725 |
ac6aef7921af37b6b53a7afd54ef920909e1314a | 73 | module AzureMediaService
class MediaProcessor < Model::Base
end
end
| 12.166667 | 36 | 0.780822 |
f816138b42bbeb8f25c961fec6f1ffa299fffdec | 1,321 | require 'yaml'
module Raml
# @private
class Parser
class << self
def parse(data, file_dir=Dir.getwd)
register_include_tag
data = YAML.load data
expand_includes data, file_dir
Root.new data
end
private
def register_include_tag
YAML.add_tag '!include', Raml::Parser::Include
end
def expand_includes(val, cwd)
case val
when Hash
val.merge!(val, &expand_includes_transform(cwd))
when Array
val.map!(&expand_includes_transform(cwd))
end
end
def expand_includes_transform(cwd)
proc do |arg1, arg2|
val = arg2.nil? ? arg1 : arg2
child_wd = cwd
if val.is_a? Raml::Parser::Include
child_wd = expand_includes_working_dir cwd, val.path
val = val.content cwd
end
expand_includes val, child_wd
val
end
end
def expand_includes_working_dir(current_wd, include_pathname)
include_path = File.dirname include_pathname
if include_path.start_with? '/'
include_path
else
"#{current_wd}/#{include_path}"
end
end
end
end
end
| 22.775862 | 67 | 0.544285 |
87f9a49239910540756964178d0c9c2eeaa39ae2 | 357 | class Dog < ApplicationRecord
include PgSearch::Model
validates :name, :age, :breed, :is_available, presence: true
paginates_per 5
scope :breed, -> (breed_parameter) { where("breed like ?", "%#{breed_parameter}%")}
pg_search_scope :search_dogs, against: [:name],
using: {
tsearch:{
any_word: true,
prefix: true
}
}
end | 21 | 85 | 0.64986 |
e8ad40b72cb920798b653d91236180321ca5f4c2 | 623 | # frozen_string_literal: true
# Copyright (c) 2019 Danil Pismenny <[email protected]>
class DepositDecorator < ApplicationDecorator
delegate_all
def self.table_columns
%i[id member_uid member created_at updated_at currency aasm_state invoice_expires_at amount fee txid txout tid transfer_type address invoice_id data]
end
def invoice_expires_at
present_time object.invoice_expires_at
end
def id
h.content_tag :span, object.id, title: object.type
end
def data
h.content_tag :span, 'data', title: object.data
end
def txid
txid_with_recorded_transaction object.txid
end
end
| 21.482759 | 153 | 0.770465 |
e285b9b51b834832496e5811b3c1c728273c49b1 | 2,219 | # Since lesson #8 is on methods, you will be writing the entire method.
# To gain more familiarity, look up the documentation for each hint.
# Remember to unskip the corresponding tests one at a time.
# method name: #ascii_translator
# parameter: number (an integer)
# return value: the number's ASCII character (https://www.ascii-code.com/)
# hint: use Integer#chr
def ascii_translator(number)
number.chr(Encoding::ASCII)
end
# method name: #common_sports
# parameters: current_sports and favorite_sports (both arrays)
# return value: an array containing items in both arrays
# hint: use Array#intersection
def common_sports(current_sports, favorite_sports)
current_sports.intersection(favorite_sports)
end
# method name: #alphabetical_list
# parameter: games (an array)
# return value: games, alphabetically sorted and duplicates removed
# hint: chain Array#sort and Array#uniq together
def alphabetical_list(games)
games.sort.uniq
end
# method name: #lucky_number
# parameter: number (an integer) with default value of 7
# return value: a string "Today's lucky number is <number>"
def lucky_number(number = 7)
"Today's lucky number is #{number}"
end
# method name: #ascii_code
# parameter: character (a string)
# return value: the character's ordinal number
# explicit return value: 'Input Error' if character's length does not equal 1
# hint: use String#ord
def ascii_code(character)
character.size != 1 ? "Input Error" : character.ord
end
# method name: #pet_pun
# parameter: animal (a string)
# return value: nil
# console output: if animal is 'cat', 'Cats are purr-fect!' (perfect)
# console output: if animal is 'dog', 'Dogs are paw-some!' (awesome)
# console output: otherwise, "I think <animal>s have pet-tential!" (potential)
# hint: use puts
def pet_pun(animal)
case animal
when 'cat'
puts 'Cats are purr-fect!'
when 'dog'
puts 'Dogs are paw-some!'
else
puts "I think #{animal}s have pet-tential!"
end
end
# method name: #twenty_first_century?
# parameter: year (an integer)
# return value: true if the year is between 2001 - 2100, otherwise return false
# hint: use Comparable#between?
def twenty_first_century?(year)
year.between?(2001, 2100)
end
| 30.819444 | 79 | 0.739522 |
339f6e2b8908bf6e376916f1416558c41c842acc | 737 | # frozen_string_literal: true
class Pry
class Config
# MemoizedValue is a Proc (block) wrapper. It is meant to be used as a
# configuration value. Subsequent `#call` calls return the same memoized
# result.
#
# @example
# num = 19
# value = Pry::Config::MemoizedValue.new { num += 1 }
# value.call # => 20
# value.call # => 20
# value.call # => 20
#
# @api private
# @since ?.?.?
# @see Pry::Config::LazyValue
class MemoizedValue
def initialize(&block)
@block = block
@called = false
@call = nil
end
def call
return @call if @called
@called = true
@call = @block.call
end
end
end
end
| 21.057143 | 76 | 0.545455 |
62cb0d3dd176760ac7211294320ef714a103efe1 | 261 | require "open-uri"
require "nokogiri"
require "pry"
require "cooking_time/version"
require_relative "cooking_time/cli.rb"
require_relative "cooking_time/scraper.rb"
require_relative "cooking_time/recipe.rb"
module CookingTime
# Your code goes here...
end
| 17.4 | 42 | 0.793103 |
f85f92a061350eccf59d343617200999e9b019a2 | 3,284 | # rubocop:disable Layout/EndOfLine
# This file is copied to spec/ when you run 'rails generate rspec:install'
require 'spec_helper'
require 'capybara/rspec'
require 'factory_bot_rails'
# require 'shoulda-matchers'
require 'support/factory_bot'
ENV['RAILS_ENV'] ||= 'test'
require File.expand_path('../config/environment', __dir__)
# Prevent database truncation if the environment is production
abort('The Rails environment is running in production mode!') if Rails.env.production?
require 'rspec/rails'
# Add additional requires below this line. Rails is not loaded until this point!
# Requires supporting ruby files with custom matchers and macros, etc, in
# spec/support/ and its subdirectories. Files matching `spec/**/*_spec.rb` are
# run as spec files by default. This means that files in spec/support that end
# in _spec.rb will both be required and run as specs, causing the specs to be
# run twice. It is recommended that you do not name files matching this glob to
# end with _spec.rb. You can configure this pattern with the --pattern
# option on the command line or in ~/.rspec, .rspec or `.rspec-local`.
#
# The following line is provided for convenience purposes. It has the downside
# of increasing the boot-up time by auto-requiring all files in the support
# directory. Alternatively, in the individual `*_spec.rb` files, manually
# require only the support files necessary.
#
# Dir[Rails.root.join('spec', 'support', '**', '*.rb')].sort.each { |f| require f }
# Checks for pending migrations and applies them before tests are run.
# If you are not using ActiveRecord, you can remove these lines.
begin
ActiveRecord::Migration.maintain_test_schema!
rescue ActiveRecord::PendingMigrationError => e
puts e.to_s.strip
exit 1
end
RSpec.configure do |config|
# Remove this line if you're not using ActiveRecord or ActiveRecord fixtures
# config.fixture_path = "#{::Rails.root}/spec/fixtures"
# If you're not using ActiveRecord, or you'd prefer not to run each of your
# examples within a transaction, remove the following line or assign false
# instead of true.
# config.use_transactional_fixtures = true
# You can uncomment this line to turn off ActiveRecord support entirely.
# config.use_active_record = false
# RSpec Rails can automatically mix in different behaviours to your tests
# based on their file location, for example enabling you to call `get` and
# `post` in specs under `spec/controllers`.
#
# You can disable this behaviour by removing the line below, and instead
# explicitly tag your specs with their type, e.g.:
#
# RSpec.describe UsersController, type: :controller do
# # ...
# end
#
# The different available types are documented in the features, such as in
# https://relishapp.com/rspec/rspec-rails/docs
# config.infer_spec_type_from_file_location!
# Filter lines from Rails gems in backtraces.
# config.filter_rails_from_backtrace!
# arbitrary gems may also be filtered via:
# config.filter_gems_from_backtrace("gem name")
end
Shoulda::Matchers.configure do |config|
config.integrate do |with|
with.test_framework :rspec
with.library :rails
end
end
# rubocop:enable Layout/EndOfLine
| 42.649351 | 87 | 0.734775 |
3327d678496d5f25a07041477bf89622d4af4459 | 930 | # frozen_string_literal: true
module Alchemy
class AttachmentsController < BaseController
before_action :load_attachment
authorize_resource class: Alchemy::Attachment
# sends file inline. i.e. for viewing pdfs/movies in browser
def show
response.headers['Content-Length'] = @attachment.file.size.to_s
send_file(
@attachment.file.path,
{
filename: @attachment.file_name,
type: @attachment.file_mime_type,
disposition: 'inline'
}
)
end
# sends file as attachment. aka download
def download
response.headers['Content-Length'] = @attachment.file.size.to_s
send_file(
@attachment.file.path, {
filename: @attachment.file_name,
type: @attachment.file_mime_type
}
)
end
private
def load_attachment
@attachment = Attachment.find(params[:id])
end
end
end
| 23.846154 | 69 | 0.639785 |
1aac19395f879c1c7fcaa0d47c702bbe8078adc9 | 120 | # Sample code from Programing Ruby, page 64
while line = gets
puts line if line =~ /start/ .. line =~ /end/
end
| 24 | 49 | 0.633333 |
180d9a784ff3de68826da6d0571735fbcc4c5114 | 1,691 | # frozen_string_literal: true
module VBADocuments
module DocumentUpload
class StatusAttributesSwagger
include Swagger::Blocks
swagger_component do
schema :DocumentUploadStatusAttributes do
key :required, %i[guid status]
property :guid do
key :description, 'The document upload identifier'
key :type, :string
key :format, :uuid
key :example, '6d8433c1-cd55-4c24-affd-f592287a7572'
end
property :status do
key :description, File.read(VBADocuments::Engine.root.join('app', 'swagger', 'vba_documents', 'document_upload', 'status_description.md'))
key :type, :string
key :enum, %i[pending uploaded received processing success error]
key :example, 'received'
end
property :code do
key :description, File.read(VBADocuments::Engine.root.join('app', 'swagger', 'vba_documents', 'document_upload', 'status_code_description.md'))
key :type, :string
end
property :message do
key :description, 'Human readable error description. Only present if status = "error"'
key :type, :string
end
property :detail do
key :description, 'Human readable error detail. Only present if status = "error"'
key :type, :string
end
property :updated_at do
key :description, 'The last time the submission was updated'
key :type, :string
key :format, 'date-time'
key :example, '2018-07-30T17:31:15.958Z'
end
end
end
end
end
end
| 33.156863 | 155 | 0.594323 |
39247b721cc639f792eb7e5d0c9527799a0b9976 | 102 | name "minion"
description "The role for docker minions"
run_list 'recipe[etcd2]', 'recipe[docker]'
| 25.5 | 43 | 0.735294 |
1c477ced965402f998d134d567a56640cf92f024 | 674 | require 'csv'
module Duracloud::Commands
class FindItems < Command
HEADERS = %i( content_id md5 size content_type modified )
def call
CSV.instance($stdout, headers: HEADERS, write_headers: true) do |csv|
CSV.foreach(infile, headers: false) do |row|
begin
item = Duracloud::Content.find(space_id: space_id, store_id: store_id, content_id: row[0], md5: row[1])
csv << HEADERS.map { |header| item.send(header) }
rescue Duracloud::NotFoundError, Duracloud::MessageDigestError => e
$stderr.puts "ERROR: Content ID #{row[0]} -- #{e.message}"
end
end
end
end
end
end
| 29.304348 | 115 | 0.618694 |
91ee816d5e61bf1617b4d42365c6efb44c361fc5 | 2,075 |
lib = File.expand_path("../lib", __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require "ma_breweries/version"
Gem::Specification.new do |spec|
spec.name = "ma_breweries"
spec.version = MaBreweries::VERSION
spec.authors = ["'Justin Beaulieu'"]
spec.email = ["'[email protected]'"]
spec.summary = %q{Cli for displaying all local breweries in Mass.}
spec.description = %q{Brewery search that allows you to find all of the local Massachusetts breweries. You are able to list all of the breweries by name in a numbered list. Also you can search all of the breweries by Name, Brewery type, and City. This CLI project is based on the Open Brewery DB API.}
spec.homepage = "https://github.com/Beaulieu527/ma_breweries"
spec.license = "MIT"
# Prevent pushing this gem to RubyGems.org. To allow pushes either set the 'allowed_push_host'
# to allow pushing to a single host or delete this section to allow pushing to any host.
# if spec.respond_to?(:metadata)
# spec.metadata["allowed_push_host"] = "TODO: Set to 'http://mygemserver.com'"
#
# spec.metadata["homepage_uri"] = spec.homepage
# spec.metadata["source_code_uri"] = "TODO: Put your gem's public repo URL here."
# spec.metadata["changelog_uri"] = "TODO: Put your gem's CHANGELOG.md URL here."
# else
# raise "RubyGems 2.0 or newer is required to protect against " \
# "public gem pushes."
# end
# Specify which files should be added to the gem when it is released.
# The `git ls-files -z` loads the files in the RubyGem that have been added into git.
spec.files = Dir.chdir(File.expand_path('..', __FILE__)) do
`git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) }
end
spec.bindir = "bin"
spec.executables = ["ma_breweries"]
spec.require_paths = ["lib"]
spec.add_development_dependency "bundler"
spec.add_development_dependency "rake"
spec.add_development_dependency "pry"
spec.add_development_dependency "gem-release"
end
| 46.111111 | 305 | 0.694458 |
87e4037d5c8662cacd568c1f43f125d220159c2e | 2,057 | class Ploticus < Formula
desc "Scriptable plotting and graphing utility"
homepage "https://ploticus.sourceforge.io/"
url "https://downloads.sourceforge.net/project/ploticus/ploticus/2.42/ploticus242_src.tar.gz"
version "2.42"
sha256 "3f29e4b9f405203a93efec900e5816d9e1b4381821881e241c08cab7dd66e0b0"
revision 1
bottle do
sha256 "5b23a77e8f83f384d8b3da9af8d1bd89832099a5dec99f1711a72f50a4d682fe" => :catalina
sha256 "b9ba4732a13508d6aba81b81c31a71ca65543fbcda431d57263f28255072087f" => :mojave
sha256 "bfdaab8cdaf7c0c97e02caea8fa79e76e7ac85704d21591ced4a59914b4c5c26" => :high_sierra
sha256 "06456d2606a86782cd75ee63f67e738e7ce33271902d3f4e7807d2061c0a5f4a" => :sierra
sha256 "088f4ba0eea75ed4b401f94331b70dd64e23f02fa0d95731fbaccf6904c8cea5" => :el_capitan
sha256 "b15be72d80abf16b348c625945de811bf1fb411b1cb329adc701bc04cfb41dd8" => :yosemite
sha256 "c2b4982907f4a9de66973cf55729fed03f17c42704593d6dbcce955ce53cd9bb" => :mavericks
end
depends_on "libpng"
def install
# Use alternate name because "pl" conflicts with macOS "pl" utility
args=["INSTALLBIN=#{bin}",
"EXE=ploticus"]
inreplace "src/pl.h", /#define\s+PREFABS_DIR\s+""/, "#define PREFABS_DIR \"#{pkgshare}\""
system "make", "-C", "src", *args
# Required because the Makefile assumes INSTALLBIN dir exists
bin.mkdir
system "make", "-C", "src", "install", *args
pkgshare.install Dir["prefabs/*"]
end
def caveats
<<~EOS
Ploticus prefabs have been installed to #{opt_pkgshare}
EOS
end
test do
assert_match "ploticus 2.", shell_output("#{bin}/ploticus -version 2>&1", 1)
(testpath/"test.in").write <<~EOS
#proc areadef
rectangle: 1 1 4 2
xrange: 0 5
yrange: 0 100
#proc xaxis:
stubs: text
Africa
Americas
Asia
Europe,\\nAustralia,\\n\& Pacific
EOS
system "#{bin}/ploticus", "-f", "test.in", "-png", "-o", "test.png"
assert_match "PNG image data", shell_output("file test.png")
end
end
| 34.864407 | 95 | 0.707341 |
e274919cb43a373bc3944f2cf9543020bb545096 | 818 | FactoryGirl.define do
POLICY_TAGS = %w(
important
priority
discussion
trivial
rfc
)
factory :policy do
title { Faker::Company.bs }
description { Faker::HipsterIpsum.paragraphs(rand(3) + 1).join("\n") }
submitter { create(:user, :with_confirmed_email) }
category
tag_list { POLICY_TAGS.sample(3).join(', ') }
state { Policy::VALID_STATES.sample }
trait :with_evidence do
after(:build) do |policy|
if policy.state == 'proposition'
3.times do
create(:evidence_item, :with_comments, policy: policy)
end
end
end
end
trait :with_comments do
after(:build) do |policy|
3.times do
create(:comment, :with_replies, commentable: policy)
end
end
end
end
end
| 19.95122 | 74 | 0.594132 |
017eb063e26453df9cc40fb96d619acd7c9945ae | 1,090 | require 'test_helper'
class CategoriesControllerTest < ActionDispatch::IntegrationTest
setup do
@category = categories(:one)
end
test "should get index" do
get categories_url
assert_response :success
end
test "should get new" do
get new_category_url
assert_response :success
end
test "should create category" do
assert_difference('Category.count') do
post categories_url, params: { category: { name: @category.name } }
end
assert_redirected_to category_url(Category.last)
end
test "should show category" do
get category_url(@category)
assert_response :success
end
test "should get edit" do
get edit_category_url(@category)
assert_response :success
end
test "should update category" do
patch category_url(@category), params: { category: { name: @category.name } }
assert_redirected_to category_url(@category)
end
test "should destroy category" do
assert_difference('Category.count', -1) do
delete category_url(@category)
end
assert_redirected_to categories_url
end
end
| 22.244898 | 81 | 0.719266 |
034e9981b6a2e5126cecc5282b0343d31e94e455 | 77 | class Vote < ActiveRecord::Base
belongs_to :votable, polymorphic: true
end
| 19.25 | 40 | 0.779221 |
79681db112f6be230f6a306f02e5b4167c877ce8 | 112 | class AddRateToClients < ActiveRecord::Migration
def change
add_column :clients, :rate, :number
end
end
| 18.666667 | 48 | 0.75 |
1d8f3e0d59e987df2d20448f438c325a011975eb | 382 | require 'formula'
class Ivy < Formula
homepage 'http://ant.apache.org/ivy/'
url 'http://www.apache.org/dyn/closer.cgi?path=ant/ivy/2.4.0/apache-ivy-2.4.0-bin.tar.gz'
sha1 '97a206e3b6ec2ce9793d2ee151fa997a12647c7f'
def install
libexec.install Dir['ivy*']
doc.install Dir['doc/*']
bin.write_jar_script libexec/"ivy-#{version}.jar", "ivy", "$JAVA_OPTS"
end
end
| 27.285714 | 91 | 0.698953 |
ab03457b3eac855e9c01b55e35516c6b6f38a6aa | 2,020 | ##
# This module requires Metasploit: https://metasploit.com/download
# Current source: https://github.com/rapid7/metasploit-framework
##
require 'winrm'
require 'net/winrm/stdin_shell'
require 'net/winrm/rex_http_transport'
module Net
module MsfWinRM
# Connection to a WinRM service, using Rex sockets
class RexWinRMConnection < WinRM::Connection
# Factory class to create a shell of the appropriate type.
# Subclassed to be able to provide a StdinShell
class ShellFactory < WinRM::Shells::ShellFactory
def create_shell(shell_type, shell_opts = {})
args = [
@connection_opts,
@transport,
@logger,
shell_opts
]
return StdinShell.new(*args) if shell_type == :stdin
super(shell_type, shell_opts)
end
end
# Creates a WinRM transport, subclassed to support Rex sockets
class TransportFactory < WinRM::HTTP::TransportFactory
def create_transport(connection_opts)
raise NotImplementedError unless connection_opts[:transport] == :rexhttp
super
end
private
def init_rexhttp_transport(opts)
RexHttpTransport.new(opts)
end
end
# Provide an adapter for logging WinRM module messages to the MSF log
class WinRMProxyLogger
def error(msg)
elog(msg, 'winrm')
end
def warn(msg)
wlog(msg, 'winrm')
end
def info(msg)
ilog(msg, 'winrm')
end
def debug(msg)
dlog(msg, 'winrm')
end
end
def shell_factory
@shell_factory ||= ShellFactory.new(@connection_opts, transport, logger)
end
def transport
@transport ||= begin
transport_factory = TransportFactory.new
transport_factory.create_transport(@connection_opts)
end
end
def configure_logger
@logger = WinRMProxyLogger.new
end
end
end
end
| 24.938272 | 82 | 0.617822 |
ed44a7a7694f3603c88031d04dc885d0206d2567 | 609 | require './config/environment'
class ApplicationController < Sinatra::Base
configure do
enable :sessions
set :session_secret, "7c554e078bd16af1669da55800461ca0b213d45f32122b1a29b0062f6e67ed3b35f889af3156765098290edd7a5f7b7f64728f8ba0c29b40cafc927743e8148a"
set :public_folder, 'public'
set :views, 'app/views'
end
get "/" do
erb :welcome
end
def logged_in?
!!User.find_by_id(session[:user_id])
end
def require_login
unless logged_in?
redirect '/login'
end
end
def owner?
unless session[:user_id] ==1
redirect '/clubs'
end
end
end
| 17.911765 | 156 | 0.712644 |
3395d257ac28d374482429646210946bd0741f43 | 15,733 | require 'tc_helper.rb'
class TestWorksheet < Test::Unit::TestCase
def setup
@p = Axlsx::Package.new
@wb = @p.workbook
@ws = @wb.add_worksheet
end
def test_pn
assert_equal(@ws.pn, "worksheets/sheet1.xml")
ws = @ws.workbook.add_worksheet
assert_equal(ws.pn, "worksheets/sheet2.xml")
end
def test_name_is_html_encoded
@ws.name = '<foo> & <bar>'
assert_equal(@ws.name, '<foo> & <bar>')
end
def test_name_exception_on_colon
assert_raises(ArgumentError) { @ws.name = 'foo:bar' }
end
def test_page_margins
assert(@ws.page_margins.is_a? Axlsx::PageMargins)
end
def test_page_margins_yeild
@ws.page_margins do |pm|
assert(pm.is_a? Axlsx::PageMargins)
assert(@ws.page_margins == pm)
end
end
def test_page_setup
assert(@ws.page_setup.is_a? Axlsx::PageSetup)
end
def test_page_setup_yield
@ws.page_setup do |ps|
assert(ps.is_a? Axlsx::PageSetup)
assert(@ws.page_setup == ps)
end
end
def test_print_options
assert(@ws.print_options.is_a? Axlsx::PrintOptions)
end
def test_print_options_yield
@ws.print_options do |po|
assert(po.is_a? Axlsx::PrintOptions)
assert(@ws.print_options == po)
end
end
def test_header_footer
assert(@ws.header_footer.is_a? Axlsx::HeaderFooter)
end
def test_header_footer_yield
@ws.header_footer do |hf|
assert(hf.is_a? Axlsx::HeaderFooter)
assert(@ws.header_footer == hf)
end
end
def test_no_autowidth
@ws.workbook.use_autowidth = false
@ws.add_row [1,2,3,4]
assert_equal(@ws.column_info[0].width, nil)
end
def test_initialization_options
page_margins = {:left => 2, :right => 2, :bottom => 2, :top => 2, :header => 2, :footer => 2}
page_setup = {:fit_to_height => 1, :fit_to_width => 1, :orientation => :landscape, :paper_width => "210mm", :paper_height => "297mm", :scale => 80}
print_options = {:grid_lines => true, :headings => true, :horizontal_centered => true, :vertical_centered => true}
header_footer = {:different_first => false, :different_odd_even => false, :odd_header => 'Header'}
optioned = @ws.workbook.add_worksheet(:name => 'bob', :page_margins => page_margins, :page_setup => page_setup, :print_options => print_options, :header_footer => header_footer, :selected => true, :show_gridlines => false)
page_margins.keys.each do |key|
assert_equal(page_margins[key], optioned.page_margins.send(key))
end
page_setup.keys.each do |key|
assert_equal(page_setup[key], optioned.page_setup.send(key))
end
print_options.keys.each do |key|
assert_equal(print_options[key], optioned.print_options.send(key))
end
header_footer.keys.each do |key|
assert_equal(header_footer[key], optioned.header_footer.send(key))
end
assert_equal(optioned.name, 'bob')
assert_equal(optioned.selected, true)
assert_equal(optioned.show_gridlines, false)
end
def test_use_gridlines
assert_raise(ArgumentError) { @ws.show_gridlines = -1.1 }
assert_nothing_raised { @ws.show_gridlines = false }
assert_equal(@ws.show_gridlines, false)
end
def test_selected
assert_raise(ArgumentError) { @ws.selected = -1.1 }
assert_nothing_raised { @ws.selected = true }
assert_equal(@ws.selected, true)
end
def test_rels_pn
assert_equal(@ws.rels_pn, "worksheets/_rels/sheet1.xml.rels")
ws = @ws.workbook.add_worksheet
assert_equal(ws.rels_pn, "worksheets/_rels/sheet2.xml.rels")
end
def test_rId
assert_equal(@ws.rId, "rId1")
ws = @ws.workbook.add_worksheet
assert_equal(ws.rId, "rId2")
end
def test_index
assert_equal(@ws.index, @ws.workbook.worksheets.index(@ws))
end
def test_dimension
@ws.add_row [1, 2, 3]
@ws.add_row [4, 5, 6]
assert_equal @ws.dimension.sqref, "A1:C2"
end
def test_dimension_with_empty_row
@ws.add_row
assert_equal "A1:AA200", @ws.dimension.sqref
end
def test_referencing
@ws.add_row [1, 2, 3]
@ws.add_row [4, 5, 6]
range = @ws["A1:C2"]
first_row = @ws[0]
last_row = @ws[1]
assert_equal(@ws.rows[0],first_row)
assert_equal(@ws.rows[1],last_row)
assert_equal(range.size, 6)
assert_equal(range.first, @ws.rows.first.cells.first)
assert_equal(range.last, @ws.rows.last.cells.last)
end
def test_add_row
assert(@ws.rows.empty?, "sheet has no rows by default")
r = @ws.add_row([1,2,3])
assert_equal(@ws.rows.size, 1, "add_row adds a row")
assert_equal(@ws.rows.first, r, "the row returned is the row added")
end
def test_add_chart
assert(@ws.workbook.charts.empty?, "the sheet's workbook should not have any charts by default")
@ws.add_chart Axlsx::Pie3DChart
assert_equal(@ws.workbook.charts.size, 1, "add_chart adds a chart to the workbook")
end
def test_drawing
assert @ws.drawing == nil
@ws.add_chart(Axlsx::Pie3DChart)
assert @ws.drawing.is_a?(Axlsx::Drawing)
end
def test_add_pivot_table
assert(@ws.workbook.pivot_tables.empty?, "the sheet's workbook should not have any pivot tables by default")
@ws.add_pivot_table 'G5:G6', 'A1:D:10'
assert_equal(@ws.workbook.pivot_tables.size, 1, "add_pivot_tables adds a pivot_table to the workbook")
end
def test_col_style
@ws.add_row [1,2,3,4]
@ws.add_row [1,2,3,4]
@ws.add_row [1,2,3,4]
@ws.add_row [1,2,3,4]
@ws.col_style( (1..2), 1, :row_offset=>1)
@ws.rows[(1..-1)].each do | r |
assert_equal(r.cells[1].style, 1)
assert_equal(r.cells[2].style, 1)
end
assert_equal(@ws.rows.first.cells[1].style, 0)
assert_equal(@ws.rows.first.cells[0].style, 0)
end
def test_col_style_with_empty_column
@ws.add_row [1,2,3,4]
@ws.add_row [1]
@ws.add_row [1,2,3,4]
assert_nothing_raised {@ws.col_style(1, 1)}
end
def test_cols
@ws.add_row [1,2,3,4]
@ws.add_row [1,2,3,4]
@ws.add_row [1,2,3,4]
@ws.add_row [1,2,3,4]
c = @ws.cols[1]
assert_equal(c.size, 4)
assert_equal(c[0].value, 2)
end
def test_row_style
@ws.add_row [1,2,3,4]
@ws.add_row [1,2,3,4]
@ws.add_row [1,2,3,4]
@ws.add_row [1,2,3,4]
@ws.row_style 1, 1, :col_offset=>1
@ws.rows[1].cells[(1..-1)].each do | c |
assert_equal(c.style, 1)
end
assert_equal(@ws.rows[1].cells[0].style, 0)
assert_equal(@ws.rows[2].cells[1].style, 0)
@ws.row_style( 1..2, 1, :col_offset => 2)
@ws.rows[(1..2)].each do |r|
r.cells[(2..-1)].each do |c|
assert_equal(c.style, 1)
end
end
end
def test_to_xml_string_fit_to_page
@ws.page_setup.fit_to_width = 1
doc = Nokogiri::XML(@ws.to_xml_string)
assert_equal(doc.xpath('//xmlns:worksheet/xmlns:sheetPr/xmlns:pageSetUpPr[@fitToPage="true"]').size, 1)
end
def test_to_xml_string_dimensions
@ws.add_row [1,2,3]
doc = Nokogiri::XML(@ws.to_xml_string)
assert_equal(doc.xpath('//xmlns:worksheet/xmlns:dimension[@ref="A1:C1"]').size, 1)
end
def test_fit_to_page_assignation_does_nothing
@ws.fit_to_page = true
assert_equal(@ws.fit_to_page?, false)
end
def test_to_xml_string_selected
@ws.selected = true
doc = Nokogiri::XML(@ws.to_xml_string)
assert_equal(doc.xpath('//xmlns:worksheet/xmlns:sheetViews/xmlns:sheetView[@tabSelected="true"]').size, 1)
end
def test_to_xml_string_show_gridlines
@ws.show_gridlines = false
doc = Nokogiri::XML(@ws.to_xml_string)
assert_equal(doc.xpath('//xmlns:worksheet/xmlns:sheetViews/xmlns:sheetView[@showGridLines="false"]').size, 1)
end
def test_to_xml_string_auto_fit_data
@ws.add_row [1, "two"]
doc = Nokogiri::XML(@ws.to_xml_string)
assert_equal(doc.xpath('//xmlns:worksheet/xmlns:cols/xmlns:col').size, 2)
end
def test_to_xml_string_sheet_data
@ws.add_row [1, "two"]
doc = Nokogiri::XML(@ws.to_xml_string)
assert_equal(doc.xpath('//xmlns:worksheet/xmlns:sheetData/xmlns:row').size, 1)
end
def test_to_xml_string_auto_filter
@ws.add_row [1, "two"]
@ws.auto_filter.range = "A1:B1"
doc = Nokogiri::XML(@ws.to_xml_string)
assert_equal(doc.xpath('//xmlns:worksheet/xmlns:autoFilter[@ref="A1:B1"]').size, 1)
end
def test_to_xml_string_merge_cells
@ws.add_row [1, "two"]
@ws.merge_cells "A1:D1"
@ws.merge_cells "E1:F1"
doc = Nokogiri::XML(@ws.to_xml_string)
assert_equal(doc.xpath('//xmlns:worksheet/xmlns:mergeCells/xmlns:mergeCell[@ref="A1:D1"]').size, 1)
assert_equal(doc.xpath('//xmlns:worksheet/xmlns:mergeCells/xmlns:mergeCell[@ref="E1:F1"]').size, 1)
end
def test_to_xml_string_sheet_protection
@ws.sheet_protection.password = 'fish'
doc = Nokogiri::XML(@ws.to_xml_string)
assert(doc.xpath('//xmlns:sheetProtection'))
end
def test_to_xml_string_page_margins
@ws.page_margins do |pm|
pm.left = 9
pm.right = 7
end
doc = Nokogiri::XML(@ws.to_xml_string)
assert_equal(doc.xpath('//xmlns:worksheet/xmlns:pageMargins[@left="9"][@right="7"]').size, 1)
end
def test_to_xml_string_page_setup
@ws.page_setup do |ps|
ps.paper_width = "210mm"
ps.scale = 80
end
doc = Nokogiri::XML(@ws.to_xml_string)
assert_equal(doc.xpath('//xmlns:worksheet/xmlns:pageSetup[@paperWidth="210mm"][@scale="80"]').size, 1)
end
def test_to_xml_string_print_options
@ws.print_options do |po|
po.grid_lines = true
po.horizontal_centered = true
end
doc = Nokogiri::XML(@ws.to_xml_string)
assert_equal(doc.xpath('//xmlns:worksheet/xmlns:printOptions[@gridLines="true"][@horizontalCentered="true"]').size, 1)
end
def test_to_xml_string_header_footer
@ws.header_footer do |hf|
hf.different_first = false
hf.different_odd_even = false
hf.odd_header = 'Test Header'
end
doc = Nokogiri::XML(@ws.to_xml_string)
assert_equal(doc.xpath('//xmlns:worksheet/xmlns:headerFooter[@differentFirst="false"][@differentOddEven="false"]').size, 1)
end
def test_to_xml_string_drawing
@ws.add_chart Axlsx::Pie3DChart
doc = Nokogiri::XML(@ws.to_xml_string)
assert_equal(doc.xpath('//xmlns:worksheet/xmlns:drawing[@r:id="rId1"]').size, 1)
end
def test_to_xml_string_tables
@ws.add_row ["one", "two"]
@ws.add_row [1, 2]
@ws.add_table "A1:B2"
doc = Nokogiri::XML(@ws.to_xml_string)
assert_equal(doc.xpath('//xmlns:worksheet/xmlns:tableParts[@count="1"]').size, 1)
assert_equal(doc.xpath('//xmlns:worksheet/xmlns:tableParts/xmlns:tablePart[@r:id="rId1"]').size, 1)
end
def test_to_xml_string
schema = Nokogiri::XML::Schema(File.open(Axlsx::SML_XSD))
doc = Nokogiri::XML(@ws.to_xml_string)
assert(schema.validate(doc).map{ |e| puts e.message; e }.empty?, "error free validation")
end
def test_styles
assert(@ws.styles.is_a?(Axlsx::Styles), 'worksheet provides access to styles')
end
def test_to_xml_string_with_illegal_chars
nasties = "\v\u2028\u0001\u0002\u0003\u0004\u0005\u0006\u0007\u0008\u001f"
@ws.add_row [nasties]
assert_equal(0, @ws.rows.last.cells.last.value.index("\v"))
assert_equal(nil,@ws.to_xml_string.index("\v"))
end
def test_to_xml_string_with_newlines
cell_with_newline = "foo\n\r\nbar"
@ws.add_row [cell_with_newline]
assert_equal("foo\n\r\nbar", @ws.rows.last.cells.last.value)
assert_not_nil(@ws.to_xml_string.index("foo \r bar"))
end
# Make sure the XML for all optional elements (like pageMargins, autoFilter, ...)
# is generated in correct order.
def test_valid_with_optional_elements
@ws.page_margins.set :left => 9
@ws.page_setup.set :fit_to_width => 1
@ws.print_options.set :headings => true
@ws.auto_filter.range = "A1:C3"
@ws.merge_cells "A4:A5"
@ws.add_chart Axlsx::Pie3DChart
@ws.add_table "E1:F3"
@ws.add_pivot_table 'G5:G6', 'A1:D10'
schema = Nokogiri::XML::Schema(File.open(Axlsx::SML_XSD))
doc = Nokogiri::XML(@ws.to_xml_string)
assert(schema.validate(doc).map { |e| puts e.message; e }.empty?, schema.validate(doc).map { |e| e.message }.join('\n'))
end
def test_relationships
@ws.add_row [1,2,3]
assert(@ws.relationships.empty?, "No Drawing relationship until you add a chart")
c = @ws.add_chart Axlsx::Pie3DChart
assert_equal(@ws.relationships.size, 1, "adding a chart creates the relationship")
c = @ws.add_chart Axlsx::Pie3DChart
assert_equal(@ws.relationships.size, 1, "multiple charts still only result in one relationship")
c = @ws.add_comment :text => 'builder', :author => 'bob', :ref => @ws.rows.last.cells.last
assert_equal(@ws.relationships.size, 4, "adding a comment adds 3 relationships")
c = @ws.add_comment :text => 'not that is a comment!', :author => 'travis', :ref => "A1"
assert_equal(@ws.relationships.size, 4, "adding multiple comments in the same worksheet should not add any additional comment relationships")
c = @ws.add_pivot_table 'G5:G6', 'A1:D10'
assert_equal(@ws.relationships.size, 5, "adding a pivot table adds 1 relationship")
end
def test_name_unique
assert_raise(ArgumentError, "worksheet name must be unique") { n = @ws.name; @ws.workbook.add_worksheet(:name=> n) }
end
def test_name_size
assert_raise(ArgumentError, "name too long!") { @ws.name = Array.new(32, "A").join() }
assert_nothing_raised { @ws.name = Array.new(31, "A").join() }
end
def test_set_fixed_width_column
@ws.add_row ["mule", "donkey", "horse"], :widths => [20, :ignore, nil]
assert(@ws.column_info.size == 3, "a data item for each column")
assert_equal(20, @ws.column_info[0].width, "adding a row with fixed width updates :fixed attribute")
assert_equal(@ws.column_info[1].width, nil, ":ignore does not set any data")
end
def test_fixed_height
@ws.add_row [1, 2, 3], :height => 40
assert_equal(40, @ws.rows[-1].height)
end
def test_set_column_width
@ws.add_row ["chasing windmills", "penut"]
@ws.column_widths nil, 0.5
assert_equal(@ws.column_info[1].width, 0.5, 'eat my width')
assert_raise(ArgumentError, 'only accept unsigned ints') { @ws.column_widths 2, 7, -1 }
assert_raise(ArgumentError, 'only accept Integer, Float or Fixnum') { @ws.column_widths 2, 7, "-1" }
end
def test_protect_range
assert(@ws.send(:protected_ranges).is_a?(Axlsx::SimpleTypedList))
assert_equal(0, @ws.send(:protected_ranges).size)
@ws.protect_range('A1:A3')
assert_equal('A1:A3', @ws.send(:protected_ranges).last.sqref)
end
def test_protect_range_with_cells
@ws.add_row [1, 2, 3]
assert_nothing_raised {@ws.protect_range(@ws.rows.first.cells) }
assert_equal('A1:C1', @ws.send(:protected_ranges).last.sqref)
end
def test_merge_cells
@ws.add_row [1,2,3]
@ws.add_row [4,5,6]
@ws.add_row [7,8,9]
@ws.merge_cells "A1:A2"
@ws.merge_cells "B2:C3"
@ws.merge_cells @ws.rows.last.cells[(0..1)]
assert_equal(@ws.send(:merged_cells).size, 3)
assert_equal(@ws.send(:merged_cells).last, "A3:B3")
end
def test_merge_cells_sorts_correctly_by_row_when_given_array
10.times do |i|
@ws.add_row [i]
end
@ws.merge_cells [@ws.rows[8].cells.first, @ws.rows[9].cells.first]
assert_equal "A9:A10", @ws.send(:merged_cells).first
end
def test_auto_filter
assert(@ws.auto_filter.range.nil?)
assert_raise(ArgumentError) { @ws.auto_filter = 123 }
@ws.auto_filter.range = "A1:D9"
assert_equal(@ws.auto_filter.range, "A1:D9")
end
def test_sheet_pr_for_auto_filter
@ws.auto_filter.range = 'A1:D9'
@ws.auto_filter.add_column 0, :filters, :filter_items => [1]
doc = Nokogiri::XML(@ws.to_xml_string)
assert(doc.xpath('//sheetPr[@filterMode="true"]'))
end
end
| 33.332627 | 226 | 0.681434 |
01bd9ba3444cafe998ad68a2c11e7f7f3ed13fa5 | 708 | module HealthSeven::V2_5_1
class BarP10 < ::HealthSeven::Message
attribute :msh, Msh, position: "MSH", require: true
attribute :sfts, Array[Sft], position: "SFT", multiple: true
attribute :evn, Evn, position: "EVN", require: true
attribute :pid, Pid, position: "PID", require: true
attribute :pv1, Pv1, position: "PV1", require: true
attribute :dg1s, Array[Dg1], position: "DG1", multiple: true
attribute :gp1, Gp1, position: "GP1", require: true
class Procedure < ::HealthSeven::SegmentGroup
attribute :pr1, Pr1, position: "PR1", require: true
attribute :gp2, Gp2, position: "GP2"
end
attribute :procedures, Array[Procedure], position: "BAR_P10.PROCEDURE", multiple: true
end
end | 44.25 | 88 | 0.710452 |
abfe4a3f644a971ceeebcf9afea15f9310e116e6 | 440 | class AddResidualHeatToChart250 < ActiveRecord::Migration[5.2]
def change
output_element = OutputElement.find_by_key('heat_network_production')
OutputElementSerie.create!(
output_element: output_element,
label: 'energy_heat_industry_residual_heat_steam_hot_water_output_curve',
color: '#00008B',
order_by: 1,
gquery: 'energy_heat_industry_residual_heat_steam_hot_water_output_curve'
)
end
end
| 31.428571 | 79 | 0.768182 |
3904108fa402fda91a1990753114424a37cc5364 | 916 | module Apiture
module Middleware
module Auth
class APIKey
def initialize(app, options)
@app = app
@id = options[:id]
@in = options[:in]
@name = options[:name]
@format = options[:format]
end
def call(env)
context = env[:context]
value = format_value(context.options[@id])
if @in == :header
env[:request_headers][@name] = value
elsif @in == :query
env[:params][@name] = value
elsif @in == :body
env[:body] = if body = env[:body]
body.merge(@name => value)
else
{ @name => value }
end
end
@app.call(env)
end
protected
def format_value(val)
return val unless @format
@format % val
end
end
end
end
end
| 22.9 | 52 | 0.456332 |
26c12e7456f021e756da6ef6d2d6c03a32bfa2fd | 496 | # Be sure to restart your server when you modify this file.
# Your secret key for verifying the integrity of signed cookies.
# If you change this key, all old signed cookies will become invalid!
# Make sure the secret is at least 30 characters and all random,
# no regular words or you'll be exposed to dictionary attacks.
Dummy::Application.config.secret_token = '7d5a0bfe7cbb73ea73f6b182c1067203cc960eecd6aad45662bd3b19a8ae40a26e5e48ee577fe939150f1eaa809904c400bc8dfb6560336dda31c65a910aec87'
| 62 | 171 | 0.832661 |
1aa90a464861734d206f764728c45a02a965d19d | 876 | module PgStream
class Processor
CALLBACK_TYPES = [:before_execute, :during_execute, :after_execute]
def initialize(stream)
@stream = stream
@callbacks = CALLBACK_TYPES.map do |type|
[type, []]
end.to_h
@row_count = 0
end
def register(args)
args.each do |type, function|
if CALLBACK_TYPES.include?(type)
@callbacks[type] << function
else
raise "#{type} is not an acceptable callback type. Types include #{CALLBACK_TYPES.join(', ')}"
end
end
@callbacks
end
def execute
@callbacks[:before_execute].each(&:call)
@stream.each_row do |row|
@row_count += 1
@callbacks[:during_execute].each { |y| y.call(row, @row_count) }
end
@callbacks[:after_execute].each { |y| y.call(@row_count) }
@row_count
end
end
end
| 25.028571 | 104 | 0.59589 |
e8fdda47ce7ac428c45b4419a9c0446f106af949 | 1,081 | =begin
#Selling Partner API for Shipment Invoicing
#The Selling Partner API for Shipment Invoicing helps you programmatically retrieve shipment invoice information in the Brazil marketplace for a selling partner’s Fulfillment by Amazon (FBA) orders.
OpenAPI spec version: v0
Generated by: https://github.com/swagger-api/swagger-codegen.git
Swagger Codegen version: 3.0.26
=end
require 'spec_helper'
require 'json'
require 'date'
# Unit tests for AmzSpApi::ShipmentInvoicingApiModel::TaxClassificationList
# Automatically generated by swagger-codegen (github.com/swagger-api/swagger-codegen)
# Please update as you see appropriate
describe 'TaxClassificationList' do
before do
# run before each test
@instance = AmzSpApi::ShipmentInvoicingApiModel::TaxClassificationList.new
end
after do
# run after each test
end
describe 'test an instance of TaxClassificationList' do
it 'should create an instance of TaxClassificationList' do
expect(@instance).to be_instance_of(AmzSpApi::ShipmentInvoicingApiModel::TaxClassificationList)
end
end
end
| 30.885714 | 198 | 0.791859 |
4afa8b8ef96f863479d731c96ac8d8f9649174c5 | 439 | # User definable key/value pairs, usually used for Farmware authorship.
class FarmwareEnv < ApplicationRecord
belongs_to :device
serialize :value
validate :primitives_only
PRIMITIVES_ONLY = "`value` must be a string, number or boolean"
def primitives_only
errors.add(:value, PRIMITIVES_ONLY) unless is_primitve
end
def is_primitve
[String, Integer, Float, TrueClass, FalseClass].include?(value.class)
end
end
| 25.823529 | 73 | 0.758542 |
1ace8d4ded95ec4fc1fdcf00ab204a7af96f8d67 | 3,865 | module Ticketbai
module Operations
# In this operation, the document is not signed and it is not encoded in Base64 when making the request to the API as issuance and annulment
# operations, instead it is directly appended to the tag FacturaEmitida of the api payload document.
class IssuanceUnsigned
# Sujetos > Destinatario
attr_reader :receiver_nif, :receiver_name
# Factura > CabeceraFactura
attr_reader :invoice_serial, :invoice_number, :invoice_date, :invoice_time
# Factura > DatosFactura
attr_reader :invoice_description, :invoice_total, :invoice_vat_key
# Factura > TipoDesglose
attr_reader :invoice_amount, :invoice_vat, :invoice_vat_total
OPERATION_NAME = :issuance_unsigned
###
# @param [String] receiver_nif Spanish NIF or official identification document in case of being another country
# @param [String] receiver_name Name of the receiver
# @param [String] receiver_country Country code of the receiver (Ex: ES|DE)
# @param [Boolean] receiver_in_eu The receiver residence is in Europe?
# @param [String] invoice_serial Invoices serial number
# @param [String] invoice_number Invoices number
# @param [String] invoice_date Invoices emission date (Format: d-m-Y)
# @param [Boolean] simplified_invoice is a simplified invoice?
# @param [String] invoice_description Invoices description text
# @param [String] invoice_total Total invoice amount
# @param [String] invoice_vat_key Key of the VAT regime
# @param [String] invoice_amount Taxable base of the invoice
# @param [Float] invoice_vat Invoice VAT (Ex: 21.0)
# @param [String] invoice_vat_total Invoices number
###
def initialize(**args)
@receiver_nif = args[:receiver_nif].strip
@receiver_name = args[:receiver_name]
@receiver_country = args[:receiver_country]&.upcase || 'ES'
@receiver_in_eu = args[:receiver_in_eu]
@invoice_serial = args[:invoice_serial]
@invoice_number = args[:invoice_number]
@invoice_date = args[:invoice_date]
@simplified_invoice = args[:simplified_invoice]
@invoice_description = args[:invoice_description]
@invoice_total = args[:invoice_total]
@invoice_vat_key = args[:invoice_vat_key]
@invoice_amount = args[:invoice_amount]
@invoice_vat = args[:invoice_vat]
@invoice_vat_total = args[:invoice_vat_total]
end
def create
build_document
end
def build_document
if @receiver_nif && @receiver_name
@receiver = Ticketbai::Nodes::Receiver.new(receiver_country: @receiver_country, receiver_nif: @receiver_nif, receiver_name: @receiver_name)
end
@invoice_header = Ticketbai::Nodes::InvoiceHeader.new(
invoice_serial: @invoice_serial,
invoice_number: @invoice_number,
invoice_date: @invoice_date,
invoice_time: @invoice_time,
simplified_invoice: @simplified_invoice
)
@invoice_data = Ticketbai::Nodes::InvoiceData.new(
invoice_description: @invoice_description,
invoice_total: @invoice_total,
invoice_vat_key: @invoice_vat_key
)
@breakdown_type = Ticketbai::Nodes::BreakdownType.new(
receiver_country: @receiver_country,
invoice_amount: @invoice_amount,
invoice_vat: @invoice_vat,
invoice_vat_total: @invoice_vat_total,
receiver_in_eu: @receiver_in_eu,
simplified_invoice: @simplified_invoice
)
Ticketbai::Documents::IssuanceUnsigned.new(
receiver: @receiver,
invoice_header: @invoice_header,
invoice_data: @invoice_data,
breakdown_type: @breakdown_type
).create
end
end
end
end
| 42.944444 | 149 | 0.682018 |
1d0c29559af7bc0af7d2a83e0e822e4ec6fefaa4 | 5,568 | # Unless explicitly stated otherwise all files in this repository are licensed under the BSD-3-Clause License.
# This product includes software developed at Datadog (https://www.datadoghq.com/).
# Copyright 2011-Present Datadog, Inc.
module Dogapi
class V1 # for namespacing
# Dashboard API
class DashboardService < Dogapi::APIService
API_VERSION = 'v1'
RESOURCE_NAME = 'dashboard'
# Create new dashboard
#
# Required arguments:
# :title => String: Title of the dashboard
# :widgets => JSON: List of widgets to display on the dashboard
# :layout_type => String: Layout type of the dashboard.
# Allowed values: 'ordered' or 'free'
# Optional arguments:
# :description => String: Description of the dashboard
# :is_read_only => Boolean: Whether this dashboard is read-only.
# If True, only the author and admins can make changes to it.
# :notify_list => JSON: List of handles of users to notify when changes are made to this dashboard
# e.g. '["[email protected]", "[email protected]"]'
# :template_variables => JSON: List of template variables for this dashboard.
# e.g. [{"name": "host", "prefix": "host", "default": "my-host"}]
# :template_variable_presets => JSON: List of template variables saved views
# e.g. {
# "name": "my_template_variable_preset",
# "template_variables": [{"name": "host", "prefix": "host", "default": "my-host"}]
# }
def create_board(title, widgets, layout_type, options)
# Required arguments
body = {
title: title,
widgets: widgets,
layout_type: layout_type
}
# Optional arguments
body[:description] = options[:description] if options[:description]
body[:is_read_only] = options[:is_read_only] if options[:is_read_only]
body[:notify_list] = options[:notify_list] if options[:notify_list]
body[:template_variables] = options[:template_variables] if options[:template_variables]
body[:template_variable_presets] = options[:template_variable_presets] if options[:template_variable_presets]
request(Net::HTTP::Post, "/api/#{API_VERSION}/#{RESOURCE_NAME}", nil, body, true)
end
# Update a dashboard
#
# Required arguments:
# :dashboard_id => String: ID of the dashboard
# :title => String: Title of the dashboard
# :widgets => JSON: List of widgets to display on the dashboard
# :layout_type => String: Layout type of the dashboard.
# Allowed values: 'ordered' or 'free'
# Optional arguments:
# :description => String: Description of the dashboard
# :is_read_only => Boolean: Whether this dashboard is read-only.
# If True, only the author and admins can make changes to it.
# :notify_list => JSON: List of handles of users to notify when changes are made to this dashboard
# e.g. '["[email protected]", "[email protected]"]'
# :template_variables => JSON: List of template variables for this dashboard.
# e.g. [{"name": "host", "prefix": "host", "default": "my-host"}]
# :template_variable_presets => JSON: List of template variables saved views
# e.g. {
# "name": "my_template_variable_preset",
# "template_variables": [{"name": "host", "prefix": "host", "default": "my-host"}]
# }
def update_board(dashboard_id, title, widgets, layout_type, options)
# Required arguments
body = {
title: title,
widgets: widgets,
layout_type: layout_type
}
# Optional arguments
body[:description] = options[:description] if options[:description]
body[:is_read_only] = options[:is_read_only] if options[:is_read_only]
body[:notify_list] = options[:notify_list] if options[:notify_list]
body[:template_variables] = options[:template_variables] if options[:template_variables]
body[:template_variable_presets] = options[:template_variable_presets] if options[:template_variable_presets]
request(Net::HTTP::Put, "/api/#{API_VERSION}/#{RESOURCE_NAME}/#{dashboard_id}", nil, body, true)
end
# Fetch the given dashboard
#
# Required argument:
# :dashboard_id => String: ID of the dashboard
def get_board(dashboard_id)
request(Net::HTTP::Get, "/api/#{API_VERSION}/#{RESOURCE_NAME}/#{dashboard_id}", nil, nil, false)
end
# Fetch all custom dashboards
def get_all_boards
request(Net::HTTP::Get, "/api/#{API_VERSION}/#{RESOURCE_NAME}", nil, nil, false)
end
# Delete the given dashboard
#
# Required argument:
# :dashboard_id => String: ID of the dashboard
def delete_board(dashboard_id)
request(Net::HTTP::Delete, "/api/#{API_VERSION}/#{RESOURCE_NAME}/#{dashboard_id}", nil, nil, false)
end
end
end
end
| 48.842105 | 121 | 0.574174 |
ede4462205fee6ccca4ff3d05b5e3c470ac35be5 | 1,499 | require "application_system_test_case"
describe "Issues", :system do
let(:issue) { issues(:one) }
it "visiting the index" do
visit issues_url
assert_selector "h1", text: "Issues"
end
it "creating a Issue" do
visit issues_url
click_on "New Issue"
fill_in "Customtargets", with: @issue.customtargets
fill_in "Description", with: @issue.description
fill_in "Index", with: @issue.index
fill_in "Rating", with: @issue.rating
fill_in "Recommendation", with: @issue.recommendation
fill_in "Severity", with: @issue.severity
fill_in "Title", with: @issue.title
fill_in "Type", with: @issue.type
click_on "Create Issue"
assert_text "Issue was successfully created"
click_on "Back"
end
it "updating a Issue" do
visit issues_url
click_on "Edit", match: :first
fill_in "Customtargets", with: @issue.customtargets
fill_in "Description", with: @issue.description
fill_in "Index", with: @issue.index
fill_in "Rating", with: @issue.rating
fill_in "Recommendation", with: @issue.recommendation
fill_in "Severity", with: @issue.severity
fill_in "Title", with: @issue.title
fill_in "Type", with: @issue.type
click_on "Update Issue"
assert_text "Issue was successfully updated"
click_on "Back"
end
it "destroying a Issue" do
visit issues_url
page.accept_confirm do
click_on "Destroy", match: :first
end
assert_text "Issue was successfully destroyed"
end
end
| 26.767857 | 57 | 0.691127 |
aceb9fbcaeb155b5ae1743064b9947cb3cfb7177 | 168 | class CreateSellers < ActiveRecord::Migration[5.0]
def change
create_table :sellers do |t|
t.string :name
t.belongs_to :coin_value
end
end
end
| 18.666667 | 50 | 0.672619 |
61d036371897e40639b85a99567d52e567e9ff11 | 190 | # frozen_string_literal: true
module Stator
MAJOR = 0
MINOR = 3
PATCH = 2
PRERELEASE = nil
VERSION = [MAJOR, MINOR, PATCH, PRERELEASE].compact.join(".")
end
| 14.615385 | 63 | 0.6 |
0831b973cbea8d5bf0dcfc551f47fdcf890eac6f | 281 | # frozen_string_literal: true
control 'Docker service' do
title 'should be running and enabled'
describe service('docker') do
it { should be_installed }
it { should be_enabled }
it { should be_running } unless %w[fedora suse].include? platform[:family]
end
end
| 23.416667 | 78 | 0.711744 |
21936a55a4eb4ff2ed4f59bef3566e6d61e5f454 | 86 | require 'application_configurator'
require 'stacks'
Hash.send(:include, HashExtension) | 28.666667 | 34 | 0.837209 |
b9c8cf90dfda15b13317ebde3ab1b2afb7fbcfc3 | 1,165 | require 'test_helper'
class ExplorersControllerTest < ActionController::TestCase
setup do
@explorer = explorers(:one)
end
test "should get index" do
get :index
assert_response :success
assert_not_nil assigns(:explorers)
end
test "should get new" do
get :new
assert_response :success
end
test "should create explorer" do
assert_difference('Explorer.count') do
post :create, explorer: { explorer_id: @explorer.explorer_id, friend_id: @explorer.friend_id }
end
assert_redirected_to explorer_path(assigns(:explorer))
end
test "should show explorer" do
get :show, id: @explorer
assert_response :success
end
test "should get edit" do
get :edit, id: @explorer
assert_response :success
end
test "should update explorer" do
put :update, id: @explorer, explorer: { explorer_id: @explorer.explorer_id, friend_id: @explorer.friend_id }
assert_redirected_to explorer_path(assigns(:explorer))
end
test "should destroy explorer" do
assert_difference('Explorer.count', -1) do
delete :destroy, id: @explorer
end
assert_redirected_to explorers_path
end
end
| 23.3 | 112 | 0.713305 |
620301586644dabd7b067310519840825fc64c42 | 1,101 | # coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'rack/haproxy_status/version'
Gem::Specification.new do |spec|
spec.name = "rack-haproxy_status"
spec.version = Rack::HaproxyStatus::VERSION
spec.authors = ["Marten Veldthuis"]
spec.email = ["[email protected]"]
spec.summary = %q{Tiny mountable app that returns an HTTP state based on contents of a file.}
spec.description = %q{This app will return 503 if a config file contains "off", which will tell HAproxy to drop this node from the balancer backend.}
spec.homepage = "https://github.com/roqua/rack-haproxy_status"
spec.license = "MIT"
spec.files = `git ls-files -z`.split("\x0")
spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) }
spec.test_files = spec.files.grep(%r{^(test|spec|features)/})
spec.require_paths = ["lib"]
spec.add_development_dependency "bundler", "~> 1.6"
spec.add_development_dependency "rake"
spec.add_development_dependency 'rspec'
end
| 44.04 | 153 | 0.683924 |
1c19027f2f4100996a4cdedcd8ad6041917c5db6 | 550 | # frozen_string_literal: true
require 'test_helper'
class CurrentExecutiveTest < Minitest::Test
def test_current_executive_query_contains_position
config = Config.new languages: %w[en es], country_wikidata_id: 'Q16'
executive = Executive.new comment: 'Test Executive',
executive_item_id: 'Q1',
positions: [{ position_item_id: 'Q1234', comment: 'Test position' }]
query = executive.terms[0].query(config)
assert_match(/\Wwd:Q1234\W/, query)
end
end
| 32.352941 | 106 | 0.64 |
f7af9a704492b5bc08f276ab0b4fb8c0d39c69bf | 2,265 | class Folly < Formula
desc "Collection of reusable C++ library artifacts developed at Facebook"
homepage "https://github.com/facebook/folly"
url "https://github.com/facebook/folly/archive/v2018.09.24.00.tar.gz"
sha256 "99b6ddb92ee9cf3db262b372ee7dc6a29fe3e2de14511ecc50458bf77fc29c6e"
revision 2
head "https://github.com/facebook/folly.git"
bottle do
cellar :any
sha256 "28840bf0a5ad104246f3a33a732cd6f479587e912eb25248e26411d0176b4178" => :mojave
sha256 "475c8170ef5e74c2fab069499b7f33438de55fad6e570d8e7f90caf684f765e9" => :high_sierra
sha256 "5704909af39dbf86429109c0f790f9d1dcb0e12cd64a238931babb2d524b7338" => :sierra
end
depends_on "cmake" => :build
depends_on "pkg-config" => :build
depends_on "boost"
depends_on "double-conversion"
depends_on "gflags"
depends_on "glog"
depends_on "libevent"
depends_on "lz4"
# https://github.com/facebook/folly/issues/451
depends_on :macos => :el_capitan
depends_on "openssl"
depends_on "snappy"
depends_on "xz"
depends_on "zstd"
# Known issue upstream. They're working on it:
# https://github.com/facebook/folly/pull/445
fails_with :gcc => "6"
def install
ENV.cxx11
mkdir "_build" do
args = std_cmake_args + %w[
-DFOLLY_USE_JEMALLOC=OFF
]
# Upstream issue 10 Jun 2018 "Build fails on macOS Sierra"
# See https://github.com/facebook/folly/issues/864
args << "-DCOMPILER_HAS_F_ALIGNED_NEW=OFF" if MacOS.version == :sierra
system "cmake", "..", *args, "-DBUILD_SHARED_LIBS=ON"
system "make"
system "make", "install"
system "make", "clean"
system "cmake", "..", *args, "-DBUILD_SHARED_LIBS=OFF"
system "make"
lib.install "libfolly.a", "folly/libfollybenchmark.a"
end
end
test do
(testpath/"test.cc").write <<~EOS
#include <folly/FBVector.h>
int main() {
folly::fbvector<int> numbers({0, 1, 2, 3});
numbers.reserve(10);
for (int i = 4; i < 10; i++) {
numbers.push_back(i * 2);
}
assert(numbers[6] == 12);
return 0;
}
EOS
system ENV.cxx, "-std=c++11", "test.cc", "-I#{include}", "-L#{lib}",
"-lfolly", "-o", "test"
system "./test"
end
end
| 29.038462 | 93 | 0.65298 |
b9eaab868522f732a485a6b28327614196e50b81 | 642 | # Copyright 2012 Trimble Navigation Ltd.
#
# License: Apache License, Version 2.0
require 'sketchup.rb'
module CommunityExtensions
module STL
IS_OSX = ( Object::RUBY_PLATFORM =~ /darwin/i ? true : false )
# Matches Sketchup.active_model.options['UnitsOptions']['LengthUnit']
UNIT_METERS = 4
UNIT_CENTIMETERS = 3
UNIT_MILLIMETERS = 2
UNIT_FEET = 1
UNIT_INCHES = 0
Sketchup::require File.join(PLUGIN_PATH, 'utils')
Sketchup::require File.join(PLUGIN_PATH, 'importer')
Sketchup::require File.join(PLUGIN_PATH, 'exporter')
end # module STL
end # module CommunityExtensions
| 25.68 | 73 | 0.686916 |
3997d211771331216f168c44afe8768edcb2a495 | 34,895 | #-- copyright
# OpenProject is a project management system.
# Copyright (C) 2012-2014 the OpenProject Foundation (OPF)
#
# 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 doc/COPYRIGHT.rdoc for more details.
#++
require File.expand_path('../../../../spec_helper', __FILE__)
describe Api::V2::PlanningElementsController, :type => :controller do
# ===========================================================
# Helpers
def self.become_admin
let(:current_user) { FactoryGirl.create(:admin) }
end
def self.become_non_member(&block)
let(:current_user) { FactoryGirl.create(:user) }
before do
projects = block ? instance_eval(&block) : [project]
projects.each do |p|
current_user.memberships.select {|m| m.project_id == p.id}.each(&:destroy)
end
end
end
def self.become_member_with_view_planning_element_permissions(&block)
let(:current_user) { FactoryGirl.create(:user) }
before do
role = FactoryGirl.create(:role, :permissions => [:view_work_packages])
projects = block ? instance_eval(&block) : [project]
projects.each do |p|
member = FactoryGirl.build(:member, :user => current_user, :project => p)
member.roles = [role]
member.save!
end
end
end
def self.become_member_with_edit_planning_element_permissions(&block)
let(:current_user) { FactoryGirl.create(:user) }
before do
role = FactoryGirl.create(:role, :permissions => [:edit_work_packages])
projects = block ? instance_eval(&block) : [project]
projects.each do |p|
member = FactoryGirl.build(:member, :user => current_user, :project => p)
member.roles = [role]
member.save!
end
end
end
def self.become_member_with_delete_planning_element_permissions(&block)
let(:current_user) { FactoryGirl.create(:user) }
before do
role = FactoryGirl.create(:role, :permissions => [:delete_work_packages])
projects = block ? instance_eval(&block) : [project]
projects.each do |p|
member = FactoryGirl.build(:member, :user => current_user, :project => project)
member.roles = [role]
member.save!
end
end
end
def work_packages_to_structs(work_packages)
work_packages.map do |model|
Struct::WorkPackage.new.tap do |s|
model.attributes.each do |attribute, value|
s.send(:"#{attribute}=", value)
end
s.child_ids = []
s.custom_values = []
end
end
end
before do
allow(User).to receive(:current).and_return current_user
FactoryGirl.create :priority, is_default: true
FactoryGirl.create :default_status
end
# ===========================================================
# API tests
describe 'index.xml' do
become_admin
describe 'w/ list of ids' do
describe 'w/ an unknown work package id' do
it 'renders an empty list' do
get 'index', :ids => '4711', :format => 'xml'
expect(assigns(:planning_elements)).to eq([])
end
end
describe 'w/ known work package ids in one project' do
let(:project) { FactoryGirl.create(:project, :identifier => 'test_project') }
let(:work_package) { FactoryGirl.create(:work_package, :project_id => project.id) }
describe 'w/o being a member or administrator' do
become_non_member
it 'renders an empty list' do
get 'index', :ids => work_package.id.to_s, :format => 'xml'
expect(assigns(:planning_elements)).to eq([])
end
end
describe 'w/ the current user being a member with view_work_packages permissions' do
become_member_with_view_planning_element_permissions
before do
get 'index', :ids => "", :format => 'xml'
end
describe 'w/o any planning elements within the project' do
it 'assigns an empty planning_elements array' do
expect(assigns(:planning_elements)).to eq([])
end
it 'renders the index builder template' do
expect(response).to render_template('planning_elements/index', :formats => ["api"])
end
end
describe 'w/ 3 planning elements within the project' do
before do
@created_planning_elements = [
FactoryGirl.create(:work_package, :project_id => project.id),
FactoryGirl.create(:work_package, :project_id => project.id),
FactoryGirl.create(:work_package, :project_id => project.id)
]
get 'index', :ids => @created_planning_elements.map(&:id).join(","), :format => 'xml'
end
it 'assigns a planning_elements array containing all three elements' do
expect(assigns(:planning_elements)).to match_array(@created_planning_elements)
end
it 'renders the index builder template' do
expect(response).to render_template('planning_elements/index', :formats => ["api"])
end
end
describe 'w/ 2 planning elements within a specific project and one PE requested' do
context 'with rewire_parents=false' do
let!(:wp_parent) { FactoryGirl.create(:work_package, project_id: project.id) }
let!(:wp_child) { FactoryGirl.create(:work_package, project_id: project.id,
parent_id: wp_parent.id) }
context 'with rewire_parents=false' do
before do
get 'index', project_id: project.id,
ids: wp_child.id.to_s,
rewire_parents: 'false',
format: 'xml'
end
it "includes the child's parent_id" do
expect(assigns(:planning_elements)[0].parent_id).to eq wp_parent.id
end
end
context 'without rewire_parents' do
# This is unbelievably inconsistent. When requesting this without a project_id,
# the rewiring is not done at all, so the parent_id can be seen with and
# without rewiring disabled.
# Passing a project_id here, so we can test this with rewiring enabled.
before do
get 'index', project_id: project.id,
ids: wp_child.id.to_s,
format: 'xml'
end
it "doesn't include child's parent_id" do
expect(assigns(:planning_elements)[0].parent_id).to eq nil
end
end
end
end
end
end
describe 'w/ known work package ids in multiple projects' do
let(:project_a) { FactoryGirl.create(:project, :identifier => 'project_a') }
let(:project_b) { FactoryGirl.create(:project, :identifier => 'project_b') }
let(:project_c) { FactoryGirl.create(:project, :identifier => 'project_c') }
before do
@project_a_wps = [
FactoryGirl.create(:work_package, :project_id => project_a.id),
FactoryGirl.create(:work_package, :project_id => project_a.id),
]
@project_b_wps = [
FactoryGirl.create(:work_package, :project_id => project_b.id),
FactoryGirl.create(:work_package, :project_id => project_b.id),
]
@project_c_wps = [
FactoryGirl.create(:work_package, :project_id => project_c.id),
FactoryGirl.create(:work_package, :project_id => project_c.id)
]
end
describe 'w/ an unknown pe in the list' do
become_admin { [project_a, project_b] }
it 'renders only existing work packages' do
get 'index', :ids => [@project_a_wps[0].id, @project_b_wps[0].id, '4171', '5555'].join(","), :format => 'xml'
expect(assigns(:planning_elements)).to match_array([@project_a_wps[0], @project_b_wps[0]])
end
end
describe 'w/ an inaccessible pe in the list' do
become_member_with_view_planning_element_permissions { [project_a, project_b] }
become_non_member { [project_c] }
it 'renders only accessable work packages' do
get 'index', :ids => [@project_a_wps[0].id, @project_b_wps[0].id, @project_c_wps[0].id, @project_c_wps[1].id].join(","), :format => 'xml'
expect(assigns(:planning_elements)).to match_array([@project_a_wps[0], @project_b_wps[0]])
end
it 'renders only accessable work packages' do
get 'index', :ids => [@project_c_wps[0].id, @project_c_wps[1].id].join(","), :format => 'xml'
expect(assigns(:planning_elements)).to match_array([])
end
end
describe 'w/ multiple work packages in multiple projects' do
become_member_with_view_planning_element_permissions { [project_a, project_b, project_c] }
it 'renders all work packages' do
get 'index', :ids => (@project_a_wps + @project_b_wps + @project_c_wps).map(&:id).join(","), :format => 'xml'
expect(assigns(:planning_elements)).to match_array(@project_a_wps + @project_b_wps + @project_c_wps)
end
end
end
describe 'w/ cross-project relations' do
before do
allow(Setting).to receive(:cross_project_work_package_relations?).and_return(true)
end
let!(:project1) { FactoryGirl.create(:project, :identifier => 'project-1') }
let!(:project2) { FactoryGirl.create(:project, :identifier => 'project-2') }
let!(:ticket_a) { FactoryGirl.create(:work_package, :project_id => project1.id) }
let!(:ticket_b) { FactoryGirl.create(:work_package, :project_id => project1.id, :parent_id => ticket_a.id) }
let!(:ticket_c) { FactoryGirl.create(:work_package, :project_id => project1.id, :parent_id => ticket_b.id) }
let!(:ticket_d) { FactoryGirl.create(:work_package, :project_id => project1.id) }
let!(:ticket_e) { FactoryGirl.create(:work_package, :project_id => project2.id, :parent_id => ticket_d.id) }
let!(:ticket_f) { FactoryGirl.create(:work_package, :project_id => project1.id, :parent_id => ticket_e.id) }
become_admin { [project1, project2] }
context 'without rewire_parents' do # equivalent to rewire_parents=true
it 'rewires ancestors correctly' do
get 'index', project_id: project1.id, :format => 'xml'
# the controller returns structs. We therefore have to filter for those
ticket_f_struct = assigns(:planning_elements).detect { |pe| pe.id == ticket_f.id }
expect(ticket_f_struct.parent_id).to eq(ticket_d.id)
end
end
context 'with rewire_parents=false' do
before do
get 'index', project_id: project1.id, format: 'xml', rewire_parents: 'false'
end
it "doesn't rewire ancestors" do
# the controller returns structs. We therefore have to filter for those
ticket_f_struct = assigns(:planning_elements).detect { |pe| pe.id == ticket_f.id }
expect(ticket_f_struct.parent_id).to eq(ticket_e.id)
end
it 'filters out invisible work packages' do
expect(assigns(:planning_elements).map(&:id)).to_not include(ticket_e.id)
end
end
end
describe 'changed since' do
let!(:work_package) do
work_package = Timecop.travel(5.hours.ago) do
wp = FactoryGirl.create(:work_package)
wp.save!
wp
end
work_package.subject = "Changed now!"
work_package.save!
work_package
end
become_admin { [work_package.project] }
shared_context 'get work packages changed since' do
before { get 'index', project_id: work_package.project_id, changed_since: timestamp, format: 'xml' }
end
describe 'valid timestamp' do
shared_examples_for 'valid timestamp' do
let(:timestamp) { (work_package.updated_at - 5.seconds).to_i }
include_context 'get work packages changed since'
it { expect(assigns(:planning_elements).collect(&:id)).to match_array([work_package.id]) }
end
shared_examples_for 'valid but early timestamp' do
let(:timestamp) { (work_package.updated_at + 5.seconds).to_i }
include_context 'get work packages changed since'
it { expect(assigns(:planning_elements)).to be_empty }
end
it_behaves_like 'valid timestamp'
it_behaves_like 'valid but early timestamp'
end
describe 'invalid timestamp' do
let(:timestamp) { 'eeek' }
include_context 'get work packages changed since'
it { expect(response.status).to eq(400) }
end
end
end
describe 'ids' do
let(:project_a) { FactoryGirl.create(:project) }
let(:project_b) { FactoryGirl.create(:project) }
let(:project_c) { FactoryGirl.create(:project) }
let!(:work_package_a) { FactoryGirl.create(:work_package,
project: project_a) }
let!(:work_package_b) { FactoryGirl.create(:work_package,
project: project_b) }
let!(:work_package_c) { FactoryGirl.create(:work_package,
project: project_c) }
let(:project_ids) { [project_a, project_b, project_c].collect(&:id).join(',') }
let(:wp_ids) { [work_package_a, work_package_b].collect(&:id) }
become_admin { [project_a, project_b, work_package_c.project] }
describe 'empty ids' do
before { get 'index', project_id: project_ids, ids: '', format: 'xml' }
it { expect(assigns(:planning_elements)).to be_empty }
end
shared_examples_for "valid ids request" do
before { get 'index', project_id: project_ids, ids: wp_ids.join(','), format: 'xml' }
subject { assigns(:planning_elements).collect(&:id) }
it { expect(subject).to include(*wp_ids) }
it { expect(subject).not_to include(*invalid_wp_ids) }
end
describe 'known ids' do
context 'single id' do
it_behaves_like "valid ids request" do
let(:wp_ids) { [work_package_a.id] }
let(:invalid_wp_ids) { [work_package_b.id, work_package_c.id] }
end
end
context 'multiple ids' do
it_behaves_like "valid ids request" do
let(:wp_ids) { [work_package_a.id, work_package_b.id] }
let(:invalid_wp_ids) { [work_package_c.id] }
end
end
end
end
describe 'w/ list of projects' do
describe 'w/ an unknown project' do
it 'renders a 404 Not Found page' do
get 'index', :project_id => 'project_x,project_b', :format => 'xml'
expect(response.response_code).to eq(404)
end
end
describe 'w/ a known project' do
let(:project) { FactoryGirl.create(:project, :identifier => 'test_project') }
describe 'w/o being a member or administrator' do
become_non_member
it 'renders a 403 Forbidden page' do
get 'index', :project_id => project.identifier, :format => 'xml'
expect(response.response_code).to eq(403)
end
end
describe 'w/ the current user being a member with view_work_packages permissions' do
become_member_with_view_planning_element_permissions
before do
get 'index', :project_id => project.id, :format => 'xml'
end
describe 'w/o any planning elements within the project' do
it 'assigns an empty planning_elements array' do
expect(assigns(:planning_elements)).to eq([])
end
it 'renders the index builder template' do
expect(response).to render_template('planning_elements/index', :formats => ["api"])
end
end
describe 'w/ 3 planning elements within the project' do
before do
created_planning_elements = [
FactoryGirl.create(:work_package, :project_id => project.id),
FactoryGirl.create(:work_package, :project_id => project.id),
FactoryGirl.create(:work_package, :project_id => project.id)
]
@created_planning_elements = work_packages_to_structs(created_planning_elements)
get 'index', :project_id => project.id, :format => 'xml'
end
it 'assigns a planning_elements array containing all three elements' do
expect(assigns(:planning_elements)).to match_array(@created_planning_elements)
end
it 'renders the index builder template' do
expect(response).to render_template('planning_elements/index', :formats => ["api"])
end
end
end
end
describe 'w/ multiple known projects' do
let(:project_a) { FactoryGirl.create(:project, :identifier => 'project_a') }
let(:project_b) { FactoryGirl.create(:project, :identifier => 'project_b') }
let(:project_c) { FactoryGirl.create(:project, :identifier => 'project_c') }
describe 'w/ an unknown project in the list' do
become_admin { [project_a, project_b] }
it 'renders a 404 Not Found page' do
get 'index', :project_id => 'project_x,project_b', :format => 'xml'
expect(response.response_code).to eq(404)
end
end
describe 'w/ a project in the list, the current user may not access' do
before { project_a; project_b }
become_non_member { [project_b] }
before do
get 'index', :project_id => 'project_a,project_b', :format => 'xml'
end
it 'assigns an empty planning_elements array' do
expect(assigns(:planning_elements)).to eq([])
end
it 'renders the index builder template' do
expect(response).to render_template('planning_elements/index', :formats => ["api"])
end
end
describe 'w/ the current user being a member with view_work_packages permission' do
become_member_with_view_planning_element_permissions { [project_a, project_b] }
before do
get 'index', :project_id => 'project_a,project_b', :format => 'xml'
end
describe 'w/o any planning elements within the project' do
it 'assigns an empty planning_elements array' do
expect(assigns(:planning_elements)).to eq([])
end
it 'renders the index builder template' do
expect(response).to render_template('planning_elements/index', :formats => ["api"])
end
end
describe 'w/ 1 planning element in project_a and 2 in project_b' do
before do
created_planning_elements = [
FactoryGirl.create(:work_package, :project_id => project_a.id),
FactoryGirl.create(:work_package, :project_id => project_b.id),
FactoryGirl.create(:work_package, :project_id => project_b.id)
]
@created_planning_elements = work_packages_to_structs(created_planning_elements)
# adding another planning element, just to make sure, that the
# result set is properly filtered
FactoryGirl.create(:work_package, :project_id => project_c.id)
get 'index', :project_id => 'project_a,project_b', :format => 'xml'
end
it 'assigns a planning_elements array containing all three elements' do
expect(assigns(:planning_elements)).to match_array(@created_planning_elements)
end
it 'renders the index builder template' do
expect(response).to render_template('planning_elements/index', :formats => ["api"])
end
end
end
end
end
end
describe 'create.xml' do
let(:project) { FactoryGirl.create(:project_with_types, :is_public => false) }
let(:author) { FactoryGirl.create(:user) }
become_admin
describe 'permissions' do
let(:planning_element) do
FactoryGirl.build(:work_package, :author => author, :project_id => project.id)
end
def fetch
post 'create', :project_id => project.identifier,
:format => 'xml',
:planning_element => planning_element.attributes
end
def expect_redirect_to
Regexp.new(api_v2_project_planning_elements_path(project))
end
let(:permission) { :edit_work_packages }
it_should_behave_like "a controller action which needs project permissions"
end
describe 'with custom fields' do
let(:type) { Type.find_by_name("None") || FactoryGirl.create(:type_standard) }
let(:custom_field) do
FactoryGirl.create :issue_custom_field,
:name => "Verse",
:field_format => "text",
:projects => [project],
:types => [type]
end
let(:planning_element) do
FactoryGirl.build(
:work_package,
:author => author,
:type => type,
:project => project)
end
it 'creates a new planning element with the given custom field value' do
post 'create',
:project_id => project.identifier,
:format => 'xml',
:planning_element => planning_element.attributes.merge(:custom_fields => [
{ :id => custom_field.id, :value => "Wurst" }])
expect(response.response_code).to eq(303)
id = response.headers["Location"].scan(/\d+/).last.to_i
wp = WorkPackage.find_by_id id
expect(wp).not_to be_nil
custom_value = wp.custom_values.find do |value|
value.custom_field.name == custom_field.name
end
expect(custom_value).not_to be_nil
expect(custom_value.value).to eq("Wurst")
end
end
end
describe 'show.xml' do
become_admin
describe 'w/o a valid planning element id' do
describe 'w/o a given project' do
it 'renders a 404 Not Found page' do
get 'show', :id => '4711', :format => 'xml'
expect(response.response_code).to eq(404)
end
end
describe 'w/ an unknown project' do
it 'renders a 404 Not Found page' do
get 'show', :project_id => '4711', :id => '1337', :format => 'xml'
expect(response.response_code).to eq(404)
end
end
describe 'w/ a known project' do
let(:project) { FactoryGirl.create(:project, :identifier => 'test_project') }
describe 'w/o being a member or administrator' do
become_non_member
it 'renders a 403 Forbidden page' do
get 'show', :project_id => project.id, :id => '1337', :format => 'xml'
expect(response.response_code).to be === 403
end
end
describe 'w/ the current user being a member' do
become_member_with_view_planning_element_permissions
it 'raises ActiveRecord::RecordNotFound errors' do
expect {
get 'show', :project_id => project.id, :id => '1337', :format => 'xml'
}.to raise_error(ActiveRecord::RecordNotFound)
end
end
end
end
describe 'w/ a valid planning element id' do
become_admin
let(:project) { FactoryGirl.create(:project, :identifier => 'test_project') }
let(:planning_element) { FactoryGirl.create(:work_package, :project_id => project.id) }
describe 'w/o a given project' do
it 'renders a 404 Not Found page' do
get 'show', :id => planning_element.id, :format => 'xml'
expect(response.response_code).to eq(404)
end
end
describe 'w/ a known project' do
describe 'w/o being a member or administrator' do
become_non_member
it 'renders a 403 Forbidden page' do
get 'show', :project_id => project.id, :id => planning_element.id, :format => 'xml'
expect(response.response_code).to eq(403)
end
end
describe 'w/ the current user being a member' do
become_member_with_view_planning_element_permissions
it 'assigns the planning_element' do
get 'show', :project_id => project.id, :id => planning_element.id, :format => 'xml'
expect(assigns(:planning_element)).to eq(planning_element)
end
it 'renders the show builder template' do
get 'show', :project_id => project.id, :id => planning_element.id, :format => 'xml'
expect(response).to render_template('planning_elements/show', :formats => ["api"])
end
end
end
end
describe 'with custom fields' do
render_views
let(:project) { FactoryGirl.create(:project) }
let(:type) { Type.find_by_name("None") || FactoryGirl.create(:type_standard) }
let(:custom_field) do
FactoryGirl.create :text_issue_custom_field,
:projects => [project],
:types => [type]
end
let(:planning_element) do
FactoryGirl.create :work_package,
:type => type,
:project => project,
:custom_values => [
CustomValue.new(:custom_field => custom_field, :value => "Mett")]
end
it "should render the custom field values" do
get 'show', :project_id => project.identifier, :id => planning_element.id, :format => 'json'
expect(response).to be_success
expect(response.header['Content-Type']).to include 'application/json'
expect(response.body).to include "Mett"
end
end
end
describe 'update.xml' do
let(:project) { FactoryGirl.create(:project, :is_public => false) }
let(:work_package) { FactoryGirl.create(:work_package) }
become_admin
describe 'permissions' do
let(:planning_element) { FactoryGirl.create(:work_package,
:project_id => project.id) }
def fetch
post 'update', :project_id => project.identifier,
:id => planning_element.id,
:planning_element => { name: "blubs" },
:format => 'xml'
end
def expect_no_content
true
end
let(:permission) { :edit_work_packages }
it_should_behave_like "a controller action which needs project permissions"
end
describe 'empty' do
before do
put :update,
project_id: work_package.project_id,
id: work_package.id,
format: :xml
end
it { expect(response.status).to eq(400) }
end
describe 'notes' do
let(:note) { "A note set by API" }
before do
put :update,
project_id: work_package.project_id,
id: work_package.id,
planning_element: { note: note },
format: :xml
end
it { expect(response.status).to eq(204) }
describe 'journals' do
subject { work_package.reload.journals }
it { expect(subject.count).to eq(2) }
it { expect(subject.last.notes).to eq(note) }
it { expect(subject.last.user).to eq(User.current) }
end
end
describe 'with custom fields' do
let(:type) { Type.find_by_name("None") || FactoryGirl.create(:type_standard) }
let(:custom_field) do
FactoryGirl.create :text_issue_custom_field,
:projects => [project],
:types => [type]
end
let(:planning_element) do
FactoryGirl.create :work_package,
:type => type,
:project => project,
:custom_values => [
CustomValue.new(:custom_field => custom_field, :value => "Mett")]
end
it 'updates the custom field value' do
put 'update',
:project_id => project.identifier,
:format => 'xml',
:id => planning_element.id,
:planning_element => {
:custom_fields => [
{ :id => custom_field.id, :value => "Wurst" }
]
}
expect(response.response_code).to eq(204)
wp = WorkPackage.find planning_element.id
custom_value = wp.custom_values.find do |value|
value.custom_field.name == custom_field.name
end
expect(custom_value).not_to be_nil
expect(custom_value.value).not_to eq("Mett")
expect(custom_value.value).to eq("Wurst")
end
end
##
# It should be possible to update a planning element's status by transmitting the
# field 'status_id'. The test tries to change a planning element's status from
# status A to B.
describe "status" do
let(:status_a) { FactoryGirl.create :status }
let(:status_b) { FactoryGirl.create :status }
let(:planning_element) { FactoryGirl.create :work_package, status: status_a }
shared_examples_for 'work package status change' do
before do
put 'update',
project_id: project.identifier,
format: 'xml',
id: planning_element.id,
planning_element: { status_id: status_b.id }
end
it { expect(response.response_code).to eq(expected_response_code) }
it { expect(WorkPackage.find(planning_element.id).status).to eq(expected_work_package_status) }
end
context 'valid workflow exists' do
let!(:workflow) { FactoryGirl.create(:workflow,
old_status: status_a,
new_status: status_b,
type_id: planning_element.type_id) }
before { planning_element.project.add_member!(current_user, workflow.role) }
it_behaves_like 'work package status change' do
let(:expected_response_code) { 204 }
let(:expected_work_package_status) { status_b }
end
end
context 'no valid workflow exists' do
it_behaves_like 'work package status change' do
let(:expected_response_code) { 422 }
let(:expected_work_package_status) { status_a }
end
end
end
end
describe 'destroy.xml' do
become_admin
describe 'w/o a valid planning element id' do
describe 'w/o a given project' do
it 'renders a 404 Not Found page' do
get 'destroy', :id => '4711', :format => 'xml'
expect(response.response_code).to eq(404)
end
end
describe 'w/ an unknown project' do
it 'renders a 404 Not Found page' do
get 'destroy', :project_id => '4711', :id => '1337', :format => 'xml'
expect(response.response_code).to eq(404)
end
end
describe 'w/ a known project' do
let(:project) { FactoryGirl.create(:project, :identifier => 'test_project') }
describe 'w/o being a member or administrator' do
become_non_member
it 'renders a 403 Forbidden page' do
get 'destroy', :project_id => project.id, :id => '1337', :format => 'xml'
expect(response.response_code).to eq(403)
end
end
describe 'w/ the current user being a member' do
become_member_with_delete_planning_element_permissions
it 'raises ActiveRecord::RecordNotFound errors' do
expect {
get 'destroy', :project_id => project.id, :id => '1337', :format => 'xml'
}.to raise_error(ActiveRecord::RecordNotFound)
end
end
end
end
describe 'w/ a valid planning element id' do
let(:project) { FactoryGirl.create(:project, :identifier => 'test_project') }
let(:planning_element) { FactoryGirl.create(:work_package, :project_id => project.id) }
describe 'w/o a given project' do
it 'renders a 404 Not Found page' do
get 'destroy', :id => planning_element.id, :format => 'xml'
expect(response.response_code).to eq(404)
end
end
describe 'w/ a known project' do
describe 'w/o being a member or administrator' do
become_non_member
it 'renders a 403 Forbidden page' do
get 'destroy', :project_id => project.id, :id => planning_element.id, :format => 'xml'
expect(response.response_code).to eq(403)
end
end
describe 'w/ the current user being a member' do
become_member_with_delete_planning_element_permissions
it 'assigns the planning_element' do
get 'destroy', :project_id => project.id, :id => planning_element.id, :format => 'xml'
expect(assigns(:planning_element)).to eq(planning_element)
end
it 'renders the destroy builder template' do
get 'destroy', :project_id => project.id, :id => planning_element.id, :format => 'xml'
expect(response).to render_template('planning_elements/destroy', :formats => ["api"])
end
it 'deletes the record' do
get 'destroy', :project_id => project.id, :id => planning_element.id, :format => 'xml'
expect {
planning_element.reload
}.to raise_error(ActiveRecord::RecordNotFound)
end
end
end
end
end
end
| 35.462398 | 149 | 0.596733 |
e25fbf453c6fa2e6f463e680762311c749bec708 | 773 | module Mutations
class CreateGrading < GraphQL::Schema::Mutation
argument :submission_id, ID, required: true
argument :grades, [Types::GradeInputType], required: true
argument :feedback, String, required: false
argument :checklist, GraphQL::Types::JSON, required: true
argument :note, String, required: false
description "Create grading for submission"
field :success, Boolean, null: false
def resolve(params)
mutator = CreateGradingMutator.new(context, params)
if mutator.valid?
mutator.grade
mutator.notify(:success, "Grades Recorded", "The submission has been marked as reviewed.")
{ success: true }
else
mutator.notify_errors
{ success: false }
end
end
end
end
| 28.62963 | 98 | 0.677878 |
382c825ab5543bf39d52045853247d65d05d8a16 | 328 | RSpec.describe NewRelic::RestApi::ApplicationMetricNames do
describe '.requested_path' do
subject(:requested_path) do
described_class.requested_path(application_id: 1)
end
it 'returns "/applications/:application_id/metrics"' do
expect(requested_path).to eq("applications/1/metrics")
end
end
end
| 27.333333 | 60 | 0.740854 |
287eb9c5c0e8e520f97a4317df074e4bf50206f3 | 87 | class FaradayCalsmock < Faraday::FaradayBase
self.base_url = CALS_API_BASE_URL
end
| 14.5 | 44 | 0.804598 |
61f3c612092d16d3b421064ec5fd787664770cef | 1,464 | class LocationsController < ApplicationController
NEAREST_LIMIT = 5
before_action :set_breadcrumbs
before_action :set_postcode
before_action :send_cache_headers
layout 'full_width_with_breadcrumbs', only: %i(show index)
def index
return render :search unless @postcode.present?
@locations = begin
Locations.nearest_to_postcode(@postcode, limit: NEAREST_LIMIT).map do |location|
LocationSearchResultDecorator.new(location)
end
rescue Geocoder::InvalidPostcode
render :invalid_postcode
rescue Geocoder::FailedLookup
render :failed_lookup
end
end
def show
location = Locations.find(params[:id])
raise(ActionController::RoutingError, 'Location Not Found') unless location
booking_location = Locations.find(location.booking_location_id) if location.booking_location_id.present?
nearest_locations = Locations.nearest_to_postcode(@postcode, limit: NEAREST_LIMIT) rescue nil
@location = LocationDecorator.new(location,
booking_location: booking_location,
nearest_locations: nearest_locations)
end
private
def set_breadcrumbs
breadcrumb Breadcrumb.book_an_appointment
breadcrumb Breadcrumb.how_to_book_face_to_face
end
def set_postcode
@postcode = params[:postcode]
end
def send_cache_headers
expires_in Rails.application.config.cache_max_age, public: true
end
end
| 28.153846 | 108 | 0.73224 |
9191f9f336f89322257adedcb35fae5de58a88e9 | 8,602 | gem 'minitest'
require 'minitest/autorun'
require 'ruby2js/filter/rubyjs'
describe Ruby2JS::Filter::RubyJS do
def to_js( string)
Ruby2JS.convert(string, filters: [Ruby2JS::Filter::RubyJS]).to_s
end
describe 'String conversions' do
it "should handle capitalize" do
to_js( 'a.capitalize()' ).must_equal '_s.capitalize(a)'
end
it "should handle center" do
to_js( 'a.center(80)' ).must_equal '_s.center(a, 80)'
end
it "should handle chomp" do
to_js( 'a.chomp()' ).must_equal '_s.chomp(a)'
end
it "should handle ljust" do
to_js( 'a.ljust(80)' ).must_equal '_s.ljust(a, 80)'
end
it "should handle lstrip" do
to_js( 'a.ljust()' ).must_equal '_s.ljust(a)'
end
it "should handle rindex" do
to_js( 'a.rindex("b")' ).must_equal '_s.rindex(a, "b")'
end
it "should handle rjust" do
to_js( 'a.rjust(80)' ).must_equal '_s.rjust(a, 80)'
end
it "should handle rstrip" do
to_js( 'a.rjust()' ).must_equal '_s.rjust(a)'
end
it "should handle scan" do
to_js( 'a.scan(/f/)' ).must_equal '_s.scan(a, /f/)'
end
it "should handle swapcase" do
to_js( 'a.swapcase()' ).must_equal '_s.swapcase(a)'
end
it "should handle tr" do
to_js( 'a.tr("a", "A")' ).must_equal '_s.tr(a, "a", "A")'
end
end
describe 'Array conversions' do
it "should handle at" do
to_js( 'a.at(3)' ).must_equal '_a.at(a, 3)'
end
it "should handle compact" do
to_js( 'a.compact' ).must_equal '_a.compact(a)'
end
it "should handle compact!" do
to_js( 'a.compact!' ).must_equal '_a.compact_bang(a)'
end
it "should handle delete_at" do
to_js( 'a.delete_at(3)' ).must_equal '_a.delete_at(a, 3)'
end
it "should handle delete_if" do
to_js( 'a.delete_if {|i| i<0}' ).
must_equal '_e.delete_if(a, function(i) {return i < 0})'
end
it "should handle each_index" do
to_js( 'a.each_index {|i| a[i]+=1}' ).
must_equal '_a.each_index(a, function(i) {a[i]++})'
end
it "should handle flatten" do
to_js( 'a.flatten' ).must_equal '_a.flatten(a)'
end
it "should handle insert" do
to_js( 'a.insert(i,3)' ).must_equal '_a.insert(a, i, 3)'
end
it "should handle keep_if" do
to_js( 'a.keep_if {|i| i<0}' ).
must_equal '_a.keep_if(a, function(i) {return i < 0})'
end
it "should handle reverse" do
to_js( 'a.reverse' ).must_equal '_a.reverse(a)'
end
it "should handle reverse!" do
to_js( 'a.reverse!' ).must_equal '_a.reverse_bang(a)'
end
it "should handle rotate" do
to_js( 'a.rotate(3)' ).must_equal '_a.rotate(a, 3)'
end
it "should handle rotate!" do
to_js( 'a.rotate!(3)' ).must_equal '_a.rotate_bang(a, 3)'
end
it "should handle select" do
to_js( 'a.select! {|i| i<0}' ).
must_equal '_a.select_bang(a, function(i) {return i < 0})'
end
it "should handle shift" do
to_js( 'a.shift(3)' ).must_equal '_a.shift(a, 3)'
end
it "should handle shuffle" do
to_js( 'a.shuffle' ).must_equal '_a.shuffle(a)'
end
it "should handle shuffle!" do
to_js( 'a.shuffle!' ).must_equal '_a.shuffle_bang(a)'
end
it "should handle slice" do
to_js( 'a.slice(i, 3)' ).must_equal '_a.slice(a, i, 3)'
end
it "should handle slice!" do
to_js( 'a.slice!(i, 3)' ).must_equal '_a.slice_bang(a, i, 3)'
end
it "should handle transpose" do
to_js( 'a.transpose' ).must_equal '_a.transpose(a)'
end
it "should handle uniq" do
to_js( 'a.uniq' ).must_equal '_a.uniq(a)'
end
it "should handle uniq_bang" do
to_js( 'a.uniq!' ).must_equal '_a.uniq_bang(a)'
end
it "should handle union" do
to_js( 'a.union(b)' ).must_equal '_a.union(a, b)'
end
end
describe 'Enumerable conversions' do
it "should handle collect_concat" do
to_js( 'a.collect_concat {|i| i}' ).
must_equal '_e.collect_concat(a, function(i) {return i})'
end
it "should handle count" do
to_js( 'a.count {|i| i % 2 == 0}' ).
must_equal '_e.count(a, function(i) {return i % 2 == 0})'
end
it "should handle drop_while" do
to_js( 'a.drop_while {|i| i < 3}' ).
must_equal '_e.drop_while(a, function(i) {return i < 3})'
end
it "should handle each_slice" do
to_js( 's.each_slice(2) {|a,b| console.log [a,b]}' ).
must_equal '_e.each_slice(s, 2, function(a, b) {console.log([a, b])})'
end
it "should handle each_with_index" do
to_js( 's.each_with_index {|a,i| console.log [a,i]}' ).
must_equal '_e.each_with_index(s, function(a, i) {console.log([a, i])})'
end
it "should handle each_with_object" do
to_js( 's.each_with_object(a) {|a,b| a << b}' ).
must_equal '_e.each_with_object(s, a, function(a, b) {a.push(b)})'
end
it "should handle find" do
to_js( 's.find(ifnone) {|a| a < 10}' ).
must_equal '_e.find(s, ifnone, function(a) {return a < 10})'
to_js( 's.find {|a| a < 10}' ).
must_equal '_e.find(s, null, function(a) {return a < 10})'
end
it "should handle find_all" do
to_js( 's.find_all {|a| a < 10}' ).
must_equal '_e.find_all(s, function(a) {return a < 10})'
end
it "should handle flat_map" do
to_js( 'a.flat_map {|i| i}' ).
must_equal '_e.flat_map(a, function(i) {return i})'
end
it "should handle inject" do
to_js( 'a.inject(init) {|i,v| i << v}' ).
must_equal '_e.inject(a, init, null, function(i, v) {i.push(v)})'
end
it "should handle grep" do
to_js( 'a.grep {|s| s =~ /x/}' ).
must_equal '_e.grep(a, function(s) {return /x/.test(s)})'
end
it "should handle group_by" do
to_js( 'a.group_by {|s| s.name}' ).
must_equal '_e.group_by(a, function(s) {return s.name})'
end
it "should handle map" do
to_js( 'a.map {|s| s.name}' ).
must_equal '_e.map(a, function(s) {return s.name})'
end
it "should handle max_by" do
to_js( 'a.max_by {|s| s.name}' ).
must_equal '_e.max_by(a, function(s) {return s.name})'
end
it "should handle min_by" do
to_js( 'a.min_by {|s| s.name}' ).
must_equal '_e.min_by(a, function(s) {return s.name})'
end
it "should handle one?" do
to_js( 'a.one? {|s| s < 0}' ).
must_equal '_e.one(a, function(s) {return s < 0})'
end
it "should handle partition" do
to_js( 'a.partition {|s| s > 0}' ).
must_equal '_e.partition(a, function(s) {return s > 0})'
end
it "should handle reject" do
to_js( 'a.reject {|s| s < 0}' ).
must_equal '_e.reject(a, function(s) {return s < 0})'
end
it "should handle reverse_each" do
to_js( 'a.reverse_each {|s| console.log s}' ).
must_equal '_e.reverse_each(a, function(s) {console.log(s)})'
end
it "should handle sort_by" do
to_js( 'a.sort_by {|s| s.age}' ).
must_equal '_e.sort_by(a, function(s) {return s.age})'
end
it "should handle take_while" do
to_js( 'a.take_while {|s| s < 0}' ).
must_equal '_e.take_while(a, function(s) {return s < 0})'
end
end
describe 'Time conversions' do
it "should handle strftime" do
to_js( 'Date.new().strftime("%Y")' ).
must_equal '_t.strftime(new Date(), "%Y")'
end
end
describe 'Comparable conversions' do
it "should handle <=>" do
to_js( '3 <=> 5' ).must_equal 'R.Comparable.cmp(3, 5)'
end
it "should between?" do
to_js( '3.between?(1,5)' ).must_equal 'R(3).between(1, 5)'
end
end
describe 'ranges' do
it "should handle inclusive ranges" do
to_js( '(1..9)' ).must_equal 'new R.Range(1, 9)'
end
it "should handle enclusive ranges" do
to_js( '(1...9)' ).must_equal 'new R.Range(1, 9, true)'
end
end
describe 'filter bypass operations' do
it 'should handle functional style calls' do
to_js( '_s.capitalize("foo")').must_equal '_s.capitalize("foo")'
end
it 'should leave alone classic ("OO") style chains' do
to_js( 'R("a").capitalize().lstrip()' ).
must_equal( 'R("a").capitalize().lstrip()' )
end
end
describe 'no input' do
it 'should do nothing with nothing' do
to_js( '').must_equal ''
end
end
describe Ruby2JS::Filter::DEFAULTS do
it "should include Functions" do
Ruby2JS::Filter::DEFAULTS.must_include Ruby2JS::Filter::Functions
end
end
end
| 27.307937 | 80 | 0.582074 |
26b453fc8740c34ca0f6343678f295359bb9523d | 2,672 | class Vnstat < Formula
desc "Console-based network traffic monitor"
homepage "https://humdi.net/vnstat/"
url "https://humdi.net/vnstat/vnstat-2.8.tar.gz"
sha256 "03f858a7abf6bd85bb8cd595f3541fc3bd31f8f400ec092ef3034825ccb77c25"
license "GPL-2.0-only"
head "https://github.com/vergoh/vnstat.git", branch: "master"
bottle do
sha256 arm64_monterey: "17d72eee03c37131ab65a80500885f44f5b96cdd242eb25dcb887a08eac29bfe"
sha256 arm64_big_sur: "1b3dd9ca73892c5a80eaf5be1e7e71a8ec7035a8539ebefff3108c169b264871"
sha256 monterey: "cf5082ac9dec5d1b11f4c67e197e60053969fb185590690eba7f83280fa46bed"
sha256 big_sur: "fd1ec9717260fdab127a4bedc0b37fa8e7ddf7cbf98f580d4a09ee83c8732fa8"
sha256 catalina: "f77d3b9d0d6255cb9e25bf8d55f4b77e65bb4d042e4967994694f86f02efc403"
sha256 mojave: "6dcdff6ebc18f04db1c1774a170111147a30a2b9b1fa9c3aede34ef0af7ed683"
sha256 x86_64_linux: "6741cfc8070a737a45db2a57c4a9fc3b9a6e505e4a1cbf97be5b37bbeb33a58e"
end
depends_on "gd"
uses_from_macos "sqlite"
def install
inreplace %w[src/cfg.c src/common.h man/vnstat.1 man/vnstatd.8 man/vnstati.1
man/vnstat.conf.5].each do |s|
s.gsub! "/etc/vnstat.conf", "#{etc}/vnstat.conf", false
s.gsub! "/var/", "#{var}/", false
s.gsub! "var/lib", "var/db", false
# https://github.com/Homebrew/homebrew-core/pull/84695#issuecomment-913043888
# network interface difference between macos and linux
s.gsub! "\"eth0\"", "\"en0\"", false if OS.mac?
end
system "./configure", "--disable-dependency-tracking",
"--disable-silent-rules",
"--prefix=#{prefix}",
"--sysconfdir=#{etc}",
"--sbindir=#{bin}",
"--localstatedir=#{var}"
system "make", "install"
end
def post_install
(var/"db/vnstat").mkpath
(var/"log/vnstat").mkpath
(var/"run/vnstat").mkpath
end
def caveats
<<~EOS
To monitor interfaces other than "en0" edit #{etc}/vnstat.conf
EOS
end
plist_options startup: true
service do
run [opt_bin/"vnstatd", "--nodaemon", "--config", etc/"vnstat.conf"]
keep_alive true
working_dir var
process_type :background
end
test do
cp etc/"vnstat.conf", testpath
inreplace "vnstat.conf", var, testpath/"var"
(testpath/"var/db/vnstat").mkpath
begin
stat = IO.popen("#{bin}/vnstatd --nodaemon --config vnstat.conf")
sleep 1
ensure
Process.kill "SIGINT", stat.pid
Process.wait stat.pid
end
assert_match "Info: Monitoring", stat.read
end
end
| 34.25641 | 93 | 0.666542 |
f8334622aa17ab36a431fdc08be0d253a4b9122a | 221 | class GemOwnershipTransfer < ActiveRecord::Base
belongs_to :old_user, class_name: "User"
belongs_to :new_user, class_name: "User"
belongs_to :ruby_gem
validates :ruby_gem, :old_user, :new_user, presence: true
end
| 31.571429 | 59 | 0.773756 |
21cb0e3f612179be33ccea17f85997788a43107d | 1,788 | # Jekyll Emoji
# https://github.com/chriskempson/jekyll-emoji
#
# A jekyll plug-in that provides a Liquid filter for emojifying text with
# https://github.com/github/gemoji. See http://www.emoji-cheat-sheet.com for
# a full listing of emoji codes.
#
# Usage:
# - Apply the filter wherever needed e.g. {{ content | emojify }}
# - Add some emoji to your article! e.g. "Hello :wink:"
require 'gemoji'
module Jekyll
module EmojiFilter
def emojify(content)
return false if !content
config = @context.registers[:site].config
if config['emoji_dir']
emoji_dir = File.join(config['baseurl'], config['emoji_dir'])
end
content.to_str.gsub(/:([a-z0-9\+\-_]+):/) do |match|
if Emoji.find_by_alias($1) and emoji_dir
'<img alt="' + $1 + '" src="' + emoji_dir + "/#{$1}.png" + '" class="emoji" width="20" height="20px" />'
else
match
end
end
end
end
class EmojiGenerator < Generator
def generate(site)
config = site.config
return false if not config['emoji_dir']
return false if config['emoji_dir'].start_with?('http')
emoji_dir = File.join(config['source'], config['emoji_dir'])
return false if File.exist?(File.join(emoji_dir, 'smiley.png'))
puts " Copying: Emoji from Gemoji to " + config['emoji_dir']
# Make Emoji directory
FileUtils.mkdir_p(emoji_dir)
# Copy Gemoji files
unicode_emoji_dir = File.join(Emoji.images_path, 'emoji')
Emoji.all.each do |em|
# Use the name rather than the unicode character
FileUtils.cp File.join(unicode_emoji_dir, em.image_filename), File.join(emoji_dir, em.name + '.png')
end
end
end
end
Liquid::Template.register_filter(Jekyll::EmojiFilter) | 29.311475 | 114 | 0.639821 |
f832c148e3b07abe7f3b1b76969046e77a64a476 | 257 | module Mongoff
class Selector < Mongoid::Criteria::Selector
def evolve_hash(serializer, value)
value = serializer.evolve_hash(value)
super
end
def multi_selection?(key)
%w($and $or $nor).include?(key.to_s)
end
end
end | 19.769231 | 46 | 0.661479 |
61771e2c97fee3f0e1374be8f8f6aa3c925a1528 | 1,075 | require 'omniauth'
require 'omniauth-google-oauth2'
require 'omniauth-mailchimp'
require 'omniauth-prayer-letters'
require 'omniauth-donorhub'
Auth::Engine.config.middleware.use OmniAuth::Builder do
provider :google_oauth2,
ENV.fetch('GOOGLE_KEY'),
ENV.fetch('GOOGLE_SECRET'),
name: 'google',
scope: 'userinfo.email,userinfo.profile,https://www.google.com/m8/feeds,https://mail.google.com/,https://www.googleapis.com/auth/calendar',
access_type: 'offline',
prompt: 'consent select_account'
provider :prayer_letters,
ENV.fetch('PRAYER_LETTERS_CLIENT_ID'),
ENV.fetch('PRAYER_LETTERS_CLIENT_SECRET'),
scope: 'contacts.read contacts.write'
provider :mailchimp,
ENV.fetch('MAILCHIMP_CLIENT_ID'),
ENV.fetch('MAILCHIMP_CLIENT_SECRET')
provider :donorhub,
ENV.fetch('DONORHUB_CLIENT_ID'),
ENV.fetch('DONORHUB_CLIENT_SECRET')
end
OmniAuth.config.on_failure = proc { |env|
OmniAuth::FailureEndpoint.new(env).redirect_to_failure
}
| 35.833333 | 150 | 0.683721 |
4a6aa0e07ba3fcc71eb9983906d1db31f58cc452 | 2,819 | require 'spec/spec_helper'
class UnsortableObject
def initialize(id)
@id = id
end
def inspect
@id.to_s
end
def ==(other)
false
end
end
describe "array.should =~ other_array" do
it "should pass if target contains all items" do
[1,2,3].should =~ [1,2,3]
end
it "should pass if target contains all items out of order" do
[1,3,2].should =~ [1,2,3]
end
it "should fail if target includes extra items" do
lambda {
[1,2,3,4].should =~ [1,2,3]
}.should fail_with(<<-MESSAGE)
expected collection contained: [1, 2, 3]
actual collection contained: [1, 2, 3, 4]
the extra elements were: [4]
MESSAGE
end
it "should fail if target is missing items" do
lambda {
[1,2].should =~ [1,2,3]
}.should fail_with(<<-MESSAGE)
expected collection contained: [1, 2, 3]
actual collection contained: [1, 2]
the missing elements were: [3]
MESSAGE
end
it "should fail if target is missing items and has extra items" do
lambda {
[1,2,4].should =~ [1,2,3]
}.should fail_with(<<-MESSAGE)
expected collection contained: [1, 2, 3]
actual collection contained: [1, 2, 4]
the missing elements were: [3]
the extra elements were: [4]
MESSAGE
end
it "should sort items in the error message if they all respond to <=>" do
lambda {
[6,2,1,5].should =~ [4,1,2,3]
}.should fail_with(<<-MESSAGE)
expected collection contained: [1, 2, 3, 4]
actual collection contained: [1, 2, 5, 6]
the missing elements were: [3, 4]
the extra elements were: [5, 6]
MESSAGE
end
it "should not sort items in the error message if they don't all respond to <=>" do
lambda {
[UnsortableObject.new(2), UnsortableObject.new(1)].should =~ [UnsortableObject.new(4), UnsortableObject.new(3)]
}.should fail_with(<<-MESSAGE)
expected collection contained: [4, 3]
actual collection contained: [2, 1]
the missing elements were: [4, 3]
the extra elements were: [2, 1]
MESSAGE
end
it "should accurately report extra elements when there are duplicates" do
lambda {
[1,1,1,5].should =~ [1,5]
}.should fail_with(<<-MESSAGE)
expected collection contained: [1, 5]
actual collection contained: [1, 1, 1, 5]
the extra elements were: [1, 1]
MESSAGE
end
it "should accurately report missing elements when there are duplicates" do
lambda {
[1,5].should =~ [1,1,5]
}.should fail_with(<<-MESSAGE)
expected collection contained: [1, 1, 5]
actual collection contained: [1, 5]
the missing elements were: [1]
MESSAGE
end
end
describe "should_not =~ [:with, :multiple, :args]" do
it "should not be supported" do
lambda {
[1,2,3].should_not =~ [1,2,3]
}.should fail_with(/Matcher does not support should_not/)
end
end
| 25.862385 | 119 | 0.642072 |
1ad280067a7f8c5115c7c5da72f60eeaea3607e6 | 2,689 | # frozen_string_literal: true
# Copyright (c) 2018 Yegor Bugayenko
#
# 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 NONINFINGEMENT. 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 'tempfile'
require_relative '../log'
require_relative '../wallet'
require_relative '../atomic_file'
# The entrance that ignores duplicates.
# Author:: Yegor Bugayenko ([email protected])
# Copyright:: Copyright (c) 2018 Yegor Bugayenko
# License:: MIT
module Zold
# The safe entrance
class NoDupEntrance
def initialize(entrance, wallets, log: Log::Quiet.new)
raise 'Entrance can\'t be nil' if entrance.nil?
@entrance = entrance
raise 'Wallets can\'t be nil' if wallets.nil?
@wallets = wallets
raise 'Log can\'t be nil' if log.nil?
@log = log
end
def start
@entrance.start { yield(self) }
end
def to_json
@entrance.to_json
end
# Returns a list of modifed wallets (as Zold::Id)
def push(id, body)
raise 'Id can\'t be nil' if id.nil?
raise 'Id must be of type Id' unless id.is_a?(Id)
raise 'Body can\'t be nil' if body.nil?
Tempfile.open(['', Wallet::EXTENSION]) do |f|
File.write(f, body)
wallet = Wallet.new(f.path)
wallet.refurbish
after = File.read(wallet.path)
wallet = @wallets.find(id)
before = wallet.exists? ? AtomicFile.new(wallet.path).read.to_s : ''
if before == after
@log.info("Duplicate of #{id}/#{wallet.digest[0, 6]}/#{after.length}b/#{wallet.txns.count}t ignored")
return []
end
@log.info("New content for #{id} arrived, #{before.length}b before and #{after.length}b after")
@entrance.push(id, body)
end
end
end
end
| 36.337838 | 111 | 0.686872 |
1a9010b899126706bbe25e4fbe940f44628b7e21 | 162 | class AddOriginalBodyToContentBlocks < ActiveRecord::Migration
def change
change_table :content_blocks do |t|
t.text :original_body
end
end
end
| 20.25 | 62 | 0.746914 |
4a5ed3c01a8980a8b837cea28923341a8d0c7d1d | 123 | require 'bundler'
Bundler.setup(:default, :development)
Bundler.require
require 'nominal'
RSpec.configure do |config|
end | 15.375 | 37 | 0.788618 |
18984e70debbc7acdcb41946777e82160ba679c7 | 913 | # == Schema Information
#
# Table name: candidates
#
# id :integer not null, primary key
# place_id :integer
# lat :float
# lon :float
# name :string(255)
# housenumber :string(255)
# street :string(255)
# postcode :string(255)
# city :string(255)
# website :string(255)
# phone :string(255)
# wheelchair :string(255)
# osm_id :integer
# osm_type :string(255)
# created_at :datetime
# updated_at :datetime
#
# Read about factories at https://github.com/thoughtbot/factory_girl
FactoryGirl.define do
sequence :osm_id do |n|
n
end
factory :candidate do
osm_id
osm_type 'node'
name "Testplace"
wheelchair "yes"
lat 52.0
lon 13.0
housenumber "23"
street "a_street"
postcode "42424"
city "Turing"
website "http://example.com"
phone "+49 30 12345678"
end
end
| 19.847826 | 68 | 0.60241 |
bf4faf275d4cd2a953b72e76337b694800aaf03e | 691 | module Spina
module Admin
class AdminController < ::Spina::ApplicationController
before_action :set_admin_locale
before_action :authorize_spina_user
def current_admin_path
request.fullpath[%r{/#{ Spina.config.backend_path }(.*)}, 1]
end
helper_method :current_admin_path
private
def set_admin_locale
I18n.locale = I18n.default_locale
end
def authorize_spina_user
redirect_to admin_login_path, flash: {information: I18n.t('spina.notifications.login')} unless current_spina_user
end
def authorize_admin
render status: 401 unless current_spina_user.admin?
end
end
end
end
| 23.827586 | 121 | 0.690304 |
28fc75719bdc16851abbdb458f7efde30cba8dd9 | 977 | Pod::Spec.new do |spec|
spec.name = 'DynamicButtonStack'
spec.module_name = 'DynamicButtonStackKit' # Module name must be different from the class name.
spec.version = '1.0.1'
spec.license = { :type => 'MIT', :file => 'License.txt' }
spec.homepage = 'https://github.com/douglashill/DynamicButtonStack'
spec.authors = { 'Douglas Hill' => 'https://twitter.com/qdoug' }
spec.summary = 'A view that dynamically lays out a collection of buttons to suit the button content and the available space.'
spec.description = <<-DESC
A view for UIKit apps that dynamically lays out a collection of UIButtons in either a column or a row to suit the button content and the available space.
DESC
spec.source = { :git => 'https://github.com/douglashill/DynamicButtonStack.git', :tag => spec.version.to_s }
spec.swift_version = '5.0'
spec.ios.deployment_target = '13.0'
spec.source_files = 'DynamicButtonStack.swift'
end
| 48.85 | 153 | 0.689867 |
d52e8349df50057d192523943012af4e81d1b80d | 339 | class CreateLines < ActiveRecord::Migration
def change
create_table :lines do |t|
t.references :scratchpad, null: false, foreign_key: true
t.integer :order, null: false
t.index [:scratchpad_id, :order], unique: true
t.text :content, null: false
t.timestamps null: false
end
end
end
| 19.941176 | 62 | 0.640118 |
bfd62a5aad059e230e338df2fa86a3f7cd79941c | 874 | Pod::Spec.new do |s|
s.name = "CloudCore"
s.summary = "Framework that enables synchronization between CloudKit and Core Data."
s.version = "3.0.1"
s.homepage = "https://github.com/deeje/CloudCore"
s.license = 'MIT'
s.author = { "deeje" => "[email protected]", "Vasily Ulianov" => "[email protected]" }
s.source = {
:git => "https://github.com/deeje/CloudCore.git",
:tag => s.version.to_s
}
s.ios.deployment_target = '10.0'
s.osx.deployment_target = '10.12'
s.tvos.deployment_target = '10.0'
s.watchos.deployment_target = '3.0'
s.source_files = 'Source/**/*.swift'
s.ios.frameworks = 'Foundation', 'CloudKit', 'CoreData'
s.osx.frameworks = 'Foundation', 'CloudKit', 'CoreData'
s.swift_versions = [5.0]
s.documentation_url = 'http://cocoadocs.org/docsets/CloudCore/'
end
| 33.615385 | 95 | 0.60984 |
abc3f7d48beafa66c039a680acbdf19c3d73b796 | 948 | # 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.
module Google
module Apis
module DatamigrationV1beta1
# Version of the google-apis-datamigration_v1beta1 gem
GEM_VERSION = "0.5.0"
# Version of the code generator used to generate this client
GENERATOR_VERSION = "0.2.0"
# Revision of the discovery document this client was generated from
REVISION = "20210413"
end
end
end
| 32.689655 | 74 | 0.734177 |
4a8f6f511d60d59cebbbb9f012b596a95e1b9b6e | 3,945 | # -*- encoding: utf-8 -*-
class UserGroupsController < ApplicationController
add_breadcrumb "I18n.t('page.configuration')", 'page_configuration_path'
add_breadcrumb "I18n.t('page.listing', :model => I18n.t('activerecord.models.user_group'))", 'user_groups_path'
add_breadcrumb "I18n.t('page.new', :model => I18n.t('activerecord.models.user_group'))", 'new_user_group_path', :only => [:new, :create]
add_breadcrumb "I18n.t('page.editing', :model => I18n.t('activerecord.models.user_group'))", 'edit_user_group_path(params[:id])', :only => [:edit, :update]
add_breadcrumb "I18n.t('activerecord.models.user_group')", 'user_group_path(params[:id])', :only => [:show]
before_filter :check_client_ip_address
load_and_authorize_resource
helper_method :get_library
before_filter :prepare_options, :except => [:index, :destroy]
class PenaltyType < Struct.new(:id, :display_name); end
# GET /user_groups
# GET /user_groups.json
def index
@user_groups = UserGroup.all
respond_to do |format|
format.html # index.html.erb
format.json { render :json => @user_groups }
end
end
# GET /user_groups/1
# GET /user_groups/1.json
def show
respond_to do |format|
format.html # show.html.erb
format.json { render :json => @user_group }
end
end
# GET /user_groups/new
def new
@user_group = UserGroup.new
prepare_options
respond_to do |format|
format.html # new.html.erb
format.json { render :json => @user_group }
end
end
# GET /user_groups/1/edit
def edit
prepare_options
end
# POST /user_groups
# POST /user_groups.json
def create
@user_group = UserGroup.new(params[:user_group])
respond_to do |format|
if @user_group.save
format.html { redirect_to @user_group, :notice => t('controller.successfully_created', :model => t('activerecord.models.user_group')) }
format.json { render :json => @user_group, :status => :created, :location => @user_group }
else
format.html { render :action => "new" }
format.json { render :json => @user_group.errors, :status => :unprocessable_entity }
end
end
end
# PUT /user_groups/1
# PUT /user_groups/1.json
def update
if params[:move]
move_position(@user_group, params[:move])
return
end
respond_to do |format|
if @user_group.update_attributes(params[:user_group])
format.html { redirect_to @user_group, :notice => t('controller.successfully_updated', :model => t('activerecord.models.user_group')) }
format.json { head :no_content }
else
format.html { render :action => "edit" }
format.json { render :json => @user_group.errors, :status => :unprocessable_entity }
end
end
end
# DELETE /user_groups/1
# DELETE /user_groups/1.json
def destroy
@user_group.destroy
respond_to do |format|
format.html { redirect_to user_groups_url }
format.json { head :no_content }
end
end
private
def prepare_options
@user_group_restrict_checkout_in_penalty_types = []
@user_group_restrict_checkout_in_penalty_types << PenaltyType.new(0, t('activerecord.attributes.user_group.restrict_checkout_in_penalty_types.no0'))
@user_group_restrict_checkout_in_penalty_types << PenaltyType.new(1, t('activerecord.attributes.user_group.restrict_checkout_in_penalty_types.yes1'))
@user_group_restrict_checkout_in_penalty_types << PenaltyType.new(2, t('activerecord.attributes.user_group.restrict_checkout_in_penalty_types.yes2'))
@user_group_restrict_checkout_after_penalty_types = []
@user_group_restrict_checkout_after_penalty_types << PenaltyType.new(0, t('activerecord.attributes.user_group.restrict_checkout_after_penalty_types.no0'))
@user_group_restrict_checkout_after_penalty_types << PenaltyType.new(1, t('activerecord.attributes.user_group.restrict_checkout_after_penalty_types.yes1'))
end
end
| 35.863636 | 159 | 0.709506 |
6a2172fe5716c81c0bf6070bd2d253639d8898a3 | 2,212 | require File.expand_path('../../../../spec_helper', __FILE__)
require 'net/ftp'
require File.expand_path('../fixtures/server', __FILE__)
describe "Net::FTP#status" do
before(:each) do
@server = NetFTPSpecs::DummyFTP.new
@server.serve_once
@ftp = Net::FTP.new
@ftp.connect("localhost", 9921)
end
after(:each) do
@ftp.quit rescue nil
@ftp.close
@server.stop
end
it "sends the STAT command to the server" do
@ftp.status
@ftp.last_response.should == "211 System status, or system help reply. (STAT)\n"
end
it "returns the received information" do
@ftp.status.should == "211 System status, or system help reply. (STAT)\n"
end
it "does not raise an error when the response code is 212" do
@server.should_receive(:stat).and_respond("212 Directory status.")
lambda { @ftp.status }.should_not raise_error
end
it "does not raise an error when the response code is 213" do
@server.should_receive(:stat).and_respond("213 File status.")
lambda { @ftp.status }.should_not raise_error
end
it "raises a Net::FTPPermError when the response code is 500" do
@server.should_receive(:stat).and_respond("500 Syntax error, command unrecognized.")
lambda { @ftp.status }.should raise_error(Net::FTPPermError)
end
it "raises a Net::FTPPermError when the response code is 501" do
@server.should_receive(:stat).and_respond("501 Syntax error in parameters or arguments.")
lambda { @ftp.status }.should raise_error(Net::FTPPermError)
end
it "raises a Net::FTPPermError when the response code is 502" do
@server.should_receive(:stat).and_respond("502 Command not implemented.")
lambda { @ftp.status }.should raise_error(Net::FTPPermError)
end
it "raises a Net::FTPTempError when the response code is 421" do
@server.should_receive(:stat).and_respond("421 Service not available, closing control connection.")
lambda { @ftp.status }.should raise_error(Net::FTPTempError)
end
it "raises a Net::FTPPermError when the response code is 530" do
@server.should_receive(:stat).and_respond("530 Requested action not taken.")
lambda { @ftp.status }.should raise_error(Net::FTPPermError)
end
end
| 34.5625 | 103 | 0.710669 |
e22ae3e6e8858a18d67bd6f35dd6b1d7957ecddd | 15,400 | # Requires that an `adaptor` let variable exist with the connected adaptor
RSpec.shared_examples 'Neo4j::Core::CypherSession::Adaptor' do
let(:real_session) do
expect(adaptor).to receive(:connect)
Neo4j::Core::CypherSession.new(adaptor)
end
let(:session_double) { double('session', adaptor: adaptor) }
before { adaptor.query(session_double, 'MATCH (n) OPTIONAL MATCH (n)-[r]-() DELETE n, r') }
subject { adaptor }
describe '#query' do
it 'Can make a query' do
adaptor.query(session_double, 'MERGE path=(n)-[rel:r]->(o) RETURN n, rel, o, path LIMIT 1')
end
it 'can make a query with a large payload' do
adaptor.query(session_double, 'CREATE (n:Test) SET n = {props} RETURN n', props: {text: 'a' * 10_000})
end
end
describe '#queries' do
it 'allows for multiple queries' do
result = adaptor.queries(session_double) do
append 'CREATE (n:Label1) RETURN n'
append 'CREATE (n:Label2) RETURN n'
end
expect(result[0].to_a[0].n).to be_a(Neo4j::Core::Node)
expect(result[1].to_a[0].n).to be_a(Neo4j::Core::Node)
if adaptor.supports_metadata?
expect(result[0].to_a[0].n.labels).to eq([:Label1])
expect(result[1].to_a[0].n.labels).to eq([:Label2])
else
expect(result[0].to_a[0].n.labels).to eq(nil)
expect(result[1].to_a[0].n.labels).to eq(nil)
end
end
it 'allows for building with Query API' do
result = adaptor.queries(session_double) do
append query.create(n: {Label1: {}}).return(:n)
end
expect(result[0].to_a[0].n).to be_a(Neo4j::Core::Node)
expect(result[0].to_a[0].n.labels).to eq(adaptor.supports_metadata? ? [:Label1] : nil)
end
end
describe 'transactions' do
def create_object_by_id(id, tx)
tx.query('CREATE (t:Temporary {id: {id}})', id: id)
end
def get_object_by_id(id, adaptor)
first = adaptor.query(session_double, 'MATCH (t:Temporary {id: {id}}) RETURN t', id: id).first
first && first.t
end
it 'logs one query per query_set in transaction' do
expect_queries(1) do
tx = adaptor.transaction(session_double)
create_object_by_id(1, tx)
tx.close
end
expect(get_object_by_id(1, adaptor)).to be_a(Neo4j::Core::Node)
expect_queries(1) do
adaptor.transaction(session_double) do |tx|
create_object_by_id(2, tx)
end
end
expect(get_object_by_id(2, adaptor)).to be_a(Neo4j::Core::Node)
end
it 'allows for rollback' do
expect_queries(1) do
tx = adaptor.transaction(session_double)
create_object_by_id(3, tx)
tx.mark_failed
tx.close
end
expect(get_object_by_id(3, adaptor)).to be_nil
expect_queries(1) do
adaptor.transaction(session_double) do |tx|
create_object_by_id(4, tx)
tx.mark_failed
end
end
expect(get_object_by_id(4, adaptor)).to be_nil
expect_queries(1) do
expect do
adaptor.transaction(session_double) do |tx|
create_object_by_id(5, tx)
fail 'Failing transaction with error'
end
end.to raise_error 'Failing transaction with error'
end
expect(get_object_by_id(5, adaptor)).to be_nil
# Nested transaction, error from inside inner transaction handled outside of inner transaction
expect_queries(1) do
adaptor.transaction(session_double) do |_tx|
expect do
adaptor.transaction(session_double) do |tx|
create_object_by_id(6, tx)
fail 'Failing transaction with error'
end
end.to raise_error 'Failing transaction with error'
end
end
expect(get_object_by_id(6, adaptor)).to be_nil
# Nested transaction, error from inside inner transaction handled outside of inner transaction
expect_queries(2) do
adaptor.transaction(session_double) do |tx|
create_object_by_id(7, tx)
expect do
adaptor.transaction(session_double) do |tx|
create_object_by_id(8, tx)
fail 'Failing transaction with error'
end
end.to raise_error 'Failing transaction with error'
end
end
expect(get_object_by_id(7, adaptor)).to be_nil
expect(get_object_by_id(8, adaptor)).to be_nil
# Nested transaction, error from inside inner transaction handled outside of outer transaction
expect_queries(1) do
expect do
adaptor.transaction(session_double) do |_tx|
adaptor.transaction(session_double) do |tx|
create_object_by_id(9, tx)
fail 'Failing transaction with error'
end
end
end.to raise_error 'Failing transaction with error'
end
expect(get_object_by_id(9, adaptor)).to be_nil
end
describe 'after_commit hook' do
it 'gets called when the root transaction is closed' do
data = false
tx1 = adaptor.transaction(session_double)
tx2 = adaptor.transaction(session_double)
tx3 = adaptor.transaction(session_double)
tx3.root.after_commit { data = true }
tx3.close
tx2.close
expect { tx1.close }.to change { data }.to(true)
expect(data).to be_truthy
end
it 'is ignored when the root transaction fails' do
data = false
tx1 = adaptor.transaction(session_double)
tx2 = adaptor.transaction(session_double)
tx3 = adaptor.transaction(session_double)
tx3.root.after_commit { data = true }
tx1.mark_failed
tx3.close
tx2.close
expect { tx1.close }.not_to change { data }
expect(data).to be_falsey
end
it 'is ignored when a child transaction fails' do
data = false
tx1 = adaptor.transaction(session_double)
tx2 = adaptor.transaction(session_double)
tx3 = adaptor.transaction(session_double)
tx3.root.after_commit { data = true }
tx3.mark_failed
tx3.close
tx2.close
expect { tx1.close }.not_to change { data }
expect(data).to be_falsey
end
end
# it 'does not allow transactions in the wrong order' do
# expect { adaptor.end_transaction }.to raise_error(RuntimeError, /Cannot close transaction without starting one/)
end
describe 'results' do
it 'handles array results' do
result = adaptor.query(session_double, "CREATE (a {b: 'c'}) RETURN [a] AS arr")
expect(result.hashes).to be_a(Array)
expect(result.hashes.size).to be(1)
expect(result.hashes[0][:arr]).to be_a(Array)
expect(result.hashes[0][:arr][0]).to be_a(Neo4j::Core::Node)
expect(result.hashes[0][:arr][0].properties).to eq(b: 'c')
end
it 'handles map results' do
result = adaptor.query(session_double, "CREATE (a {b: 'c'}) RETURN {foo: a} AS map")
expect(result.hashes).to be_a(Array)
expect(result.hashes.size).to be(1)
expect(result.hashes[0][:map]).to be_a(Hash)
expect(result.hashes[0][:map][:foo]).to be_a(Neo4j::Core::Node)
expect(result.hashes[0][:map][:foo].properties).to eq(b: 'c')
end
it 'handles map results with arrays' do
result = adaptor.query(session_double, "CREATE (a {b: 'c'}) RETURN {foo: [a]} AS map")
expect(result.hashes).to be_a(Array)
expect(result.hashes.size).to be(1)
expect(result.hashes[0][:map]).to be_a(Hash)
expect(result.hashes[0][:map][:foo]).to be_a(Array)
expect(result.hashes[0][:map][:foo][0]).to be_a(Neo4j::Core::Node)
expect(result.hashes[0][:map][:foo][0].properties).to eq(b: 'c')
end
it 'symbolizes keys for Neo4j objects' do
result = adaptor.query(session_double, 'RETURN {a: 1} AS obj')
expect(result.hashes).to eq([{obj: {a: 1}}])
structs = result.structs
expect(structs).to be_a(Array)
expect(structs.size).to be(1)
expect(structs[0].obj).to eq(a: 1)
end
describe 'parameter input and output' do
subject { adaptor.query(session_double, 'WITH {param} AS param RETURN param', param: param).first.param }
[
# Integers
rand(10_000_000_000) * -1,
rand(99_999_999) * -1,
-1, 0, 1,
rand(99_999_999),
rand(10_000_000_000),
# Floats
rand * 10_000_000_000 * -1,
rand * 99_999_999 * -1,
-18.6288,
-1.0, 0.0, 1.0,
18.6288,
rand * 99_999_999,
rand * 10_000_000_000,
# Strings
'',
'foo',
# 'bar' * 10_000, # (16326 - 16329) 16,384 = 2^14
'bar' * 5442,
# Arrays
[],
[1, 3, 5],
%w[foo bar],
# Hashes / Maps
{},
{a: 1, b: 2},
{a: 'foo', b: 'bar'}
].each do |value|
let_context(param: value) { it { should eq(value) } }
end
# Asymetric values
# Symbols
# Commented out because Embedded doesn't deal with this well...
# let_context(param: :foo) { it { should eq('foo') } }
# Sets
# Commented out because, while Bolt supports this, the default `to_json`
# makes Sets into strings (like "#<Set:0x00007f98f21174b0>"), not arrays when serializing
# let_context(param: Set.new([1, 2, 3])) { it { should eq([1, 2, 3]) } }
# let_context(param: Set.new([1, 2, 3])) { it { should eq([1, 2, 3]) } }
end
describe 'wrapping' do
let(:query) do
"MERGE path=(n:Foo {a: 1})-[r:foo {b: 2}]->(b:Foo)
RETURN #{return_clause} AS result"
end
subject { adaptor.query(session_double, query, {}, wrap_level: wrap_level).to_a[0].result }
# `wrap_level: nil` should resolve to `wrap_level: :core_entity`
[nil, :core_entity].each do |type|
let_context wrap_level: type do
let_context return_clause: 'n' do
it { should be_a(Neo4j::Core::Node) }
its(:properties) { should eq(a: 1) }
end
let_context return_clause: 'r' do
it { should be_a(Neo4j::Core::Relationship) }
its(:properties) { should eq(b: 2) }
end
let_context return_clause: 'path' do
it { should be_a(Neo4j::Core::Path) }
end
let_context(return_clause: '{c: 3}') { it { should eq(c: 3) } }
let_context(return_clause: '[1,3,5]') { it { should eq([1, 3, 5]) } }
let_context(return_clause: '["foo", "bar"]') { it { should eq(%w[foo bar]) } }
end
end
# Possible to return better data structure for :none?
let_context wrap_level: :none do
let_context(return_clause: 'n') { it { should eq(a: 1) } }
let_context(return_clause: 'r') { it { should eq(b: 2) } }
let_context(return_clause: 'path') { it { should eq([{a: 1}, {b: 2}, {}]) } }
let_context(return_clause: '{c: 3}') { it { should eq(c: 3) } }
let_context(return_clause: '[1,3,5]') { it { should eq([1, 3, 5]) } }
let_context(return_clause: '["foo", "bar"]') { it { should eq(%w[foo bar]) } }
end
let_context wrap_level: :proc do
before do
# Normally I don't think you wouldn't wrap nodes/relationships/paths
# with the same class. It's just expedient to do so in this spec
stub_const 'WrapperClass', Struct.new(:wrapped_object)
%i[Node Relationship Path].each do |core_class|
Neo4j::Core.const_get(core_class).wrapper_callback(WrapperClass.method(:new))
end
end
after do
%i[Node Relationship Path].each do |core_class|
Neo4j::Core.const_get(core_class).clear_wrapper_callback
end
end
let_context return_clause: 'n' do
it { should be_a(WrapperClass) }
its(:wrapped_object) { should be_a(Neo4j::Core::Node) }
its(:'wrapped_object.properties') { should eq(a: 1) }
end
let_context return_clause: 'r' do
it { should be_a(WrapperClass) }
its(:wrapped_object) { should be_a(Neo4j::Core::Relationship) }
its(:'wrapped_object.properties') { should eq(b: 2) }
end
let_context return_clause: 'path' do
it { should be_a(WrapperClass) }
its(:wrapped_object) { should be_a(Neo4j::Core::Path) }
end
let_context(return_clause: '{c: 3}') { it { should eq(c: 3) } }
let_context(return_clause: '[1,3,5]') { it { should eq([1, 3, 5]) } }
let_context(return_clause: '["foo", "bar"]') { it { should eq(%w[foo bar]) } }
end
end
end
describe 'cypher errors' do
describe 'unique constraint error' do
before { delete_schema(real_session) }
before { create_constraint(real_session, :Album, :uuid, type: :unique) }
it 'raises an error' do
adaptor.query(real_session, "CREATE (:Album {uuid: 'dup'})").to_a
expect do
adaptor.query(real_session, "CREATE (:Album {uuid: 'dup'})").to_a
end.to raise_error(::Neo4j::Core::CypherSession::SchemaErrors::ConstraintValidationFailedError)
end
end
describe 'Invalid input error' do
it 'raises an error' do
expect do
adaptor.query(real_session, "CRATE (:Album {uuid: 'dup'})").to_a
end.to raise_error(::Neo4j::Core::CypherSession::CypherError, /Invalid input 'A'/)
end
end
describe 'Clause ordering error' do
it 'raises an error' do
expect do
adaptor.query(real_session, "RETURN a CREATE (a:Album {uuid: 'dup'})").to_a
end.to raise_error(::Neo4j::Core::CypherSession::CypherError, /RETURN can only be used at the end of the query/)
end
end
end
describe 'schema inspection' do
before { delete_schema(real_session) }
before do
create_constraint(real_session, :Album, :al_id, type: :unique)
create_constraint(real_session, :Album, :name, type: :unique)
create_constraint(real_session, :Song, :so_id, type: :unique)
create_index(real_session, :Band, :ba_id)
create_index(real_session, :Band, :fisk)
create_index(real_session, :Person, :name)
end
describe 'constraints' do
let(:label) {}
subject { adaptor.constraints(real_session) }
it do
should match_array([
{type: :uniqueness, label: :Album, properties: [:al_id]},
{type: :uniqueness, label: :Album, properties: [:name]},
{type: :uniqueness, label: :Song, properties: [:so_id]}
])
end
end
describe 'indexes' do
let(:label) {}
subject { adaptor.indexes(real_session) }
it do
should match_array([
a_hash_including(label: :Band, properties: [:ba_id]),
a_hash_including(label: :Band, properties: [:fisk]),
a_hash_including(label: :Person, properties: [:name]),
a_hash_including(label: :Album, properties: [:al_id]),
a_hash_including(label: :Album, properties: [:name]),
a_hash_including(label: :Song, properties: [:so_id])
])
end
end
end
end
| 35.648148 | 120 | 0.596364 |
bf913eb947be9bd4ee036eebe62a1ba8288a8e29 | 165 | class AddActiveJobIdToTransactions < ActiveRecord::Migration[5.1]
def change
add_column :cangaroo_transactions, :active_job_id, :string, index: true
end
end
| 27.5 | 75 | 0.787879 |
b983b0ca73fd339eb415d32dfebc0fd8dc243594 | 36 | module Edge
VERSION = "0.6.0"
end
| 9 | 19 | 0.638889 |
e22978d5eb93a92f74370851d98fae48e0b86f5e | 331 | cask 'thunderbird-uk' do
version '38.5.1'
sha256 'af35281921fed9b6ca3964106d72c30269f52644101c5e8c8fc855cf61d6aba6'
url "https://download.mozilla.org/?product=thunderbird-#{version}&os=osx&lang=uk"
name 'Mozilla Thunderbird'
homepage 'https://www.mozilla.org/uk/thunderbird/'
license :mpl
app 'Thunderbird.app'
end
| 27.583333 | 83 | 0.76435 |
398a6c749faced821a7bbfa473e4539acb7cf8c4 | 152 | class CreateHogs < ActiveRecord::Migration
def change
create_table :hogs do |t|
t.string :name
t.integer :user_id
end
end
end
| 13.818182 | 42 | 0.651316 |
d5250d6aca43e815b5527a59211f6a4265c64ae5 | 308 | class Jitsi < Cask
version '2.4'
sha256 'ceb6b2ab04206a51faf1dbffb704a7a60ae2b7c47834b50f87da5557f543ad13'
url 'https://download.jitsi.org/jitsi/macosx/jitsi-2.4-latest.dmg'
appcast 'https://download.jitsi.org/jitsi/macosx/sparkle/updates.xml'
homepage 'https://jitsi.org/'
app 'Jitsi.app'
end
| 28 | 75 | 0.762987 |
268fadee0afc50b1094be09b45823aa37a987274 | 1,342 | # frozen_string_literal: true
require 'spec_helper'
require Rails.root.join('db', 'post_migrate', '20190313092516_clean_up_noteable_id_for_notes_on_commits.rb')
RSpec.describe CleanUpNoteableIdForNotesOnCommits do
let(:notes) { table(:notes) }
before do
notes.create!(noteable_type: 'Commit', commit_id: '3d0a182204cece4857f81c6462720e0ad1af39c9', noteable_id: 3, note: 'Test')
notes.create!(noteable_type: 'Commit', commit_id: '3d0a182204cece4857f81c6462720e0ad1af39c9', noteable_id: 3, note: 'Test')
notes.create!(noteable_type: 'Commit', commit_id: '3d0a182204cece4857f81c6462720e0ad1af39c9', noteable_id: 3, note: 'Test')
notes.create!(noteable_type: 'Issue', noteable_id: 1, note: 'Test')
notes.create!(noteable_type: 'MergeRequest', noteable_id: 1, note: 'Test')
notes.create!(noteable_type: 'Snippet', noteable_id: 1, note: 'Test')
end
it 'clears noteable_id for notes on commits' do
expect { migrate! }.to change { dirty_notes_on_commits.count }.from(3).to(0)
end
it 'does not clear noteable_id for other notes' do
expect { migrate! }.not_to change { other_notes.count }
end
def dirty_notes_on_commits
notes.where(noteable_type: 'Commit').where.not(noteable_id: nil)
end
def other_notes
notes.where("noteable_type != 'Commit' AND noteable_id IS NOT NULL")
end
end
| 38.342857 | 127 | 0.743666 |
91857af4f370503d27c79cfb26ea20d3c01163f7 | 61 | require "addressable/uri"
require 'google_custom_search_api'
| 20.333333 | 34 | 0.852459 |
e2ab68e6aae0e6ec492e214d25886a5d406d68df | 471 | module Spree
Product.class_eval do
translates :name, :description, :meta_description, :meta_keywords, :slug,
:fallbacks_for_empty_translations => true
include SpreeI18n::Translatable
def duplicate_extra(old_product)
duplicate_translations(old_product)
end
private
def duplicate_translations(old_product)
old_product.translations.each do |translation|
self.translations << translation.dup
end
end
end
end
| 23.55 | 77 | 0.726115 |
26245186bd3f7b85d06c9a313c51aca22749f3c8 | 823 | cask 'texstudio-beta' do
version '2.12.18beta1'
sha256 '1dfa02edb649545f4c99f6f121cf395d4f5eec86c347118bacd622ee4950f40d'
# github.com/texstudio-org/texstudio was verified as official when first introduced to the cask
url "https://github.com/texstudio-org/texstudio/releases/download/#{version}/texstudio-#{version}-osx.dmg"
appcast 'https://github.com/texstudio-org/texstudio/releases.atom'
name 'TeXstudio'
homepage 'https://texstudio.org/'
conflicts_with cask: 'texstudio'
app 'texstudio.app'
zap trash: [
'~/Library/Application Support/com.apple.sharedfilelist/com.apple.LSSharedFileList.ApplicationRecentDocuments/texstudio.sfl*',
'~/Library/Preferences/texstudio.plist',
'~/Library/Saved Application State/texstudio.savedState',
]
end
| 39.190476 | 141 | 0.730255 |
0816c68fbdbfe387c81fc077500d57f6f2598fd2 | 158 | class CreateBlockTypes < ActiveRecord::Migration
def change
create_table :block_types do |t|
t.string :name
t.timestamps
end
end
end
| 15.8 | 48 | 0.683544 |
0844de6a83aca34824175c742de0a1638c71fbb1 | 326 | module Dnsimple
module Commands
class ServiceDescribe
def execute(args, options = {})
short_name = args.shift
service = Service.find(short_name)
puts "\t#{service.name} (short: #{service.short_name}, id: #{service.id})"
puts "\t\t#{service.description}"
end
end
end
end
| 25.076923 | 82 | 0.616564 |
016bfd14c984831c68a8ca21e6ccf91ecf369d14 | 7,255 | require 'spec_helper'
describe Mongo::Collection::View do
let(:filter) do
{}
end
let(:options) do
{}
end
let(:view) do
described_class.new(authorized_collection, filter, options)
end
after do
authorized_collection.delete_many
end
describe '#==' do
context 'when the other object is not a collection view' do
let(:other) { 'test' }
it 'returns false' do
expect(view).to_not eq(other)
end
end
context 'when the views have the same collection, filter, and options' do
let(:other) do
described_class.new(authorized_collection, filter, options)
end
it 'returns true' do
expect(view).to eq(other)
end
end
context 'when two views have a different collection' do
let(:other_collection) do
authorized_client[:other]
end
let(:other) do
described_class.new(other_collection, filter, options)
end
it 'returns false' do
expect(view).not_to eq(other)
end
end
context 'when two views have a different filter' do
let(:other_filter) do
{ 'name' => 'Emily' }
end
let(:other) do
described_class.new(authorized_collection, other_filter, options)
end
it 'returns false' do
expect(view).not_to eq(other)
end
end
context 'when two views have different options' do
let(:other_options) do
{ 'limit' => 20 }
end
let(:other) do
described_class.new(authorized_collection, filter, other_options)
end
it 'returns false' do
expect(view).not_to eq(other)
end
end
end
describe 'copy' do
let(:view_clone) do
view.clone
end
it 'dups the options' do
expect(view.options).not_to be(view_clone.options)
end
it 'dups the filter' do
expect(view.filter).not_to be(view_clone.filter)
end
it 'references the same collection' do
expect(view.collection).to be(view_clone.collection)
end
end
describe '#each' do
let(:documents) do
(1..10).map{ |i| { field: "test#{i}" }}
end
before do
authorized_collection.insert_many(documents)
end
after do
authorized_collection.delete_many
end
context 'when a block is not provided' do
let(:enumerator) do
view.each
end
it 'returns an enumerator' do
enumerator.each do |doc|
expect(doc).to have_key('field')
end
end
end
describe '#close_query' do
let(:options) do
{ :batch_size => 1 }
end
let(:cursor) do
view.instance_variable_get(:@cursor)
end
before do
view.to_enum.next
cursor.instance_variable_set(:@cursor_id, 1) unless find_command_enabled?
end
it 'sends a kill cursors command for the cursor' do
expect(cursor).to receive(:kill_cursors).and_call_original
view.close_query
end
end
end
describe '#hash' do
let(:other) do
described_class.new(authorized_collection, filter, options)
end
it 'returns a unique value based on collection, filter, options' do
expect(view.hash).to eq(other.hash)
end
context 'when two views only have different collections' do
let(:other_collection) do
authorized_client[:other]
end
let(:other) do
described_class.new(other_collection, filter, options)
end
it 'returns different hash values' do
expect(view.hash).not_to eq(other.hash)
end
end
context 'when two views only have different filter' do
let(:other_filter) do
{ 'name' => 'Emily' }
end
let(:other) do
described_class.new(authorized_collection, other_filter, options)
end
it 'returns different hash values' do
expect(view.hash).not_to eq(other.hash)
end
end
context 'when two views only have different options' do
let(:other_options) do
{ 'limit' => 20 }
end
let(:other) do
described_class.new(authorized_collection, filter, other_options)
end
it 'returns different hash values' do
expect(view.hash).not_to eq(other.hash)
end
end
end
describe '#initialize' do
context 'when the filter is not a valid document' do
let(:filter) do
'y'
end
let(:options) do
{ limit: 5 }
end
it 'raises an error' do
expect do
view
end.to raise_error(Mongo::Error::InvalidDocument)
end
end
context 'when the filter and options are standard' do
let(:filter) do
{ 'name' => 'test' }
end
let(:options) do
{ 'sort' => { 'name' => 1 }}
end
it 'parses a standard filter' do
expect(view.filter).to eq(filter)
end
it 'parses standard options' do
expect(view.options).to eq(options)
end
end
context 'when the filter contains modifiers' do
let(:filter) do
{ :$query => { :name => 'test' }, :$comment => 'testing' }
end
let(:options) do
{ :sort => { name: 1 }}
end
it 'parses a standard filter' do
expect(view.filter).to eq('name' => 'test')
end
it 'parses standard options' do
expect(view.options).to eq('sort' => { 'name' => 1 }, 'comment' => 'testing')
end
end
context 'when the options contain modifiers' do
let(:filter) do
{ 'name' => 'test' }
end
let(:options) do
{ :sort => { name: 1 }, :modifiers => { :$comment => 'testing'}}
end
it 'parses a standard filter' do
expect(view.filter).to eq('name' => 'test')
end
it 'parses standard options' do
expect(view.options).to eq('sort' => { 'name' => 1 }, 'comment' => 'testing')
end
end
context 'when the filter and options both contain modifiers' do
let(:filter) do
{ :$query => { 'name' => 'test' }, :$hint => { name: 1 }}
end
let(:options) do
{ :sort => { name: 1 }, :modifiers => { :$comment => 'testing' }}
end
it 'parses a standard filter' do
expect(view.filter).to eq('name' => 'test')
end
it 'parses standard options' do
expect(view.options).to eq(
'sort' => { 'name' => 1 }, 'comment' => 'testing', 'hint' => { 'name' => 1 }
)
end
end
end
describe '#inspect' do
context 'when there is a namespace, filter, and options' do
let(:options) do
{ 'limit' => 5 }
end
let(:filter) do
{ 'name' => 'Emily' }
end
it 'returns a string' do
expect(view.inspect).to be_a(String)
end
it 'returns a string containing the collection namespace' do
expect(view.inspect).to match(/.*#{authorized_collection.namespace}.*/)
end
it 'returns a string containing the filter' do
expect(view.inspect).to match(/.*#{filter.inspect}.*/)
end
it 'returns a string containing the options' do
expect(view.inspect).to match(/.*#{options.inspect}.*/)
end
end
end
end
| 21.27566 | 86 | 0.580152 |
7933b2d18961332d8fc7fbdb452e2400df5ec055 | 1,232 | require 'spec_helper'
describe UsersController do
let(:user) { Factory(:user) }
before { login(user) }
context ".dashboard" do
before { get :dashboard }
specify { response.should render_template(:dashboard) }
specify { assigns(:albums).should == user.albums }
specify { assigns(:events).should be }
specify { assigns(:photos).should be }
end
context ".index" do
before { get :index }
specify { response.should render_template(:index) }
specify { assigns(:users).should == User.all }
end
context ".show" do
before { get :show }
specify { response.should render_template(:show) }
end
context ".update" do
it "should succeed with valid data" do
user.should_receive(:update_attributes).and_return(true)
post :update
response.should redirect_to(account_url)
end
it "should fail with invalid data" do
user.should_receive(:update_attributes).and_return(false)
post :update
response.should render_template(:edit)
end
end
context ".destroy" do
before { delete :destroy }
specify { response.should redirect_to(login_url) }
specify { flash[:notice].should == "Your account has been cancelled" }
end
end
| 26.212766 | 74 | 0.67289 |
18e122333322fd1ee87a7cdfbe6756e78b2889e0 | 1,878 | require File.expand_path('../../../spec_helper', __FILE__)
require File.expand_path('../fixtures/classes', __FILE__)
describe "Enumerable#zip" do
it "combines each element of the receiver with the element of the same index in arrays given as arguments" do
EnumerableSpecs::Numerous.new(1,2,3).zip([4,5,6],[7,8,9]).should == [[1,4,7],[2,5,8],[3,6,9]]
EnumerableSpecs::Numerous.new(1,2,3).zip.should == [[1],[2],[3]]
end
it "passes each element of the result array to a block and return nil if a block is given" do
expected = [[1,4,7],[2,5,8],[3,6,9]]
EnumerableSpecs::Numerous.new(1,2,3).zip([4,5,6],[7,8,9]) do |result_component|
result_component.should == expected.shift
end.should == nil
expected.size.should == 0
end
it "fills resulting array with nils if an argument array is too short" do
EnumerableSpecs::Numerous.new(1,2,3).zip([4,5,6], [7,8]).should == [[1,4,7],[2,5,8],[3,6,nil]]
end
ruby_version_is ''...'1.9' do
it "converts arguments to arrays using #to_a" do
convertable = EnumerableSpecs::ArrayConvertable.new(4,5,6)
EnumerableSpecs::Numerous.new(1,2,3).zip(convertable).should == [[1,4],[2,5],[3,6]]
convertable.called.should == :to_a
end
end
ruby_version_is '1.9' do
it "converts arguments to arrays using #to_ary" do
convertable = EnumerableSpecs::ArrayConvertable.new(4,5,6)
EnumerableSpecs::Numerous.new(1,2,3).zip(convertable).should == [[1,4],[2,5],[3,6]]
convertable.called.should == :to_ary
end
#RHO: crash
=begin
it "converts arguments to arrays using #to_ary 2" do
convertable = EnumerableSpecs::EnumConvertable.new(4..6)
EnumerableSpecs::Numerous.new(1,2,3).zip(convertable).should == [[1,4],[2,5],[3,6]]
convertable.called.should == :to_enum
convertable.sym.should == :each
end
=end
#RHO
end
end
| 36.115385 | 111 | 0.657082 |
332d1bce33e612db63c4d3d94e02098a6c009c40 | 751 | ## send it to the backends
def Sendit(metricpath, metricvalue, metrictimestamp)
if !$graphiteserver.nil? and !$graphiteserver.empty?
require 'SendGraphite'
# puts metricpath + " " + metricvalue.to_s + " " + metrictimestamp.to_s
SendGraphite metricpath, metricvalue, metrictimestamp
end
if !$gmondserver.nil? and !$gmondserver.empty?
require 'SendGanglia'
SendGanglia metricpath, metricvalue
end
if !$opentsdbserver.nil? and !$opentsdbserver.empty?
require 'SendOpenTSDB'
a = metricpath.split(/\./,2)
metric = a[0]
tag = a[1]
# Note: I really don't know if this is a sensible way to do this for
# OpenTSDB... anyone have feedback? (dlutzy)
SendOpenTSDB metric, metricvalue, metrictimestamp, "tag=" + tag
end
end
| 30.04 | 73 | 0.71771 |
872aef34fecbfffa3192bce4a0b453d57c4a5e3a | 22,461 | # Copyright 2016 LINE
#
# LINE Corporation licenses this file to you under the Apache License,
# version 2.0 (the "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at:
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
require 'base64'
require 'net/http'
require 'openssl'
require 'uri'
module Line
module Bot
# API Client of LINE Bot SDK Ruby
#
# @client ||= Line::Bot::Client.new do |config|
# config.channel_id = ENV["LINE_CHANNEL_ID"]
# config.channel_secret = ENV["LINE_CHANNEL_SECRET"]
# config.channel_token = ENV["LINE_CHANNEL_TOKEN"]
# end
class Client
# @return [String]
attr_accessor :channel_token, :channel_id, :channel_secret, :endpoint, :blob_endpoint
# @return [Object]
attr_accessor :httpclient
# @return [Hash]
attr_accessor :http_options
# Initialize a new client.
#
# @param options [Hash]
# @return [Line::Bot::Client]
def initialize(options = {})
options.each do |key, value|
instance_variable_set("@#{key}", value)
end
yield(self) if block_given?
end
def httpclient
@httpclient ||= HTTPClient.new(http_options)
end
def endpoint
@endpoint ||= API::DEFAULT_ENDPOINT
end
def blob_endpoint
return @blob_endpoint if @blob_endpoint
@blob_endpoint = if endpoint == API::DEFAULT_ENDPOINT
API::DEFAULT_BLOB_ENDPOINT
else
# for backward compatible
endpoint
end
end
# @return [Hash]
def credentials
{
"Authorization" => "Bearer #{channel_token}",
}
end
# Issue channel access token
#
# @param grant_type [String] Grant type
#
# @return [Net::HTTPResponse]
def issue_channel_token(grant_type = 'client_credentials')
channel_id_required
channel_secret_required
endpoint_path = '/oauth/accessToken'
payload = URI.encode_www_form(
grant_type: grant_type,
client_id: channel_id,
client_secret: channel_secret
)
headers = { 'Content-Type' => 'application/x-www-form-urlencoded' }
post(endpoint, endpoint_path, payload, headers)
end
# Revoke channel access token
#
# @return [Net::HTTPResponse]
def revoke_channel_token(access_token)
endpoint_path = '/oauth/revoke'
payload = URI.encode_www_form(access_token: access_token)
headers = { 'Content-Type' => 'application/x-www-form-urlencoded' }
post(endpoint, endpoint_path, payload, headers)
end
# Push messages to a user using user_id.
#
# @param user_id [String] User Id
# @param messages [Hash or Array] Message Objects
# @return [Net::HTTPResponse]
def push_message(user_id, messages)
channel_token_required
messages = [messages] if messages.is_a?(Hash)
endpoint_path = '/bot/message/push'
payload = { to: user_id, messages: messages }.to_json
post(endpoint, endpoint_path, payload, credentials)
end
# Reply messages to a user using replyToken.
#
# @example Send a balloon to a user.
# message = {
# type: 'text',
# text: 'Hello, World!'
# }
# client.reply_message(event['replyToken'], message)
#
# @example Send multiple balloons to a user.
#
# messages = [
# {type: 'text', text: 'Message1'},
# {type: 'text', text: 'Message2'}
# ]
# client.reply_message(event['replyToken'], messages)
#
# @param token [String] Reply Token
# @param messages [Hash or Array] Message Objects
# @return [Net::HTTPResponse]
def reply_message(token, messages)
channel_token_required
messages = [messages] if messages.is_a?(Hash)
endpoint_path = '/bot/message/reply'
payload = { replyToken: token, messages: messages }.to_json
post(endpoint, endpoint_path, payload, credentials)
end
# Send messages to multiple users using userIds.
#
# @param to [Array or String] Array of userIds
# @param messages [Hash or Array] Message Objects
# @return [Net::HTTPResponse]
def multicast(to, messages)
channel_token_required
to = [to] if to.is_a?(String)
messages = [messages] if messages.is_a?(Hash)
endpoint_path = '/bot/message/multicast'
payload = { to: to, messages: messages }.to_json
post(endpoint, endpoint_path, payload, credentials)
end
# Send messages to all friends.
#
# @param messages [Hash or Array] Message Objects
# @return [Net::HTTPResponse]
def broadcast(messages)
channel_token_required
messages = [messages] if messages.is_a?(Hash)
endpoint_path = '/bot/message/broadcast'
payload = { messages: messages }.to_json
post(endpoint, endpoint_path, payload, credentials)
end
# Narrowcast messages to users
#
# API Documentation is here.
# https://developers.line.biz/en/reference/messaging-api/#send-narrowcast-message
#
# @param messages [Hash or Array]
# @param recipient [Hash]
# @param filter [Hash]
# @param limit [Hash]
#
# @return [Net::HTTPResponse]
def narrowcast(messages, recipient: nil, filter: nil, limit: nil)
channel_token_required
messages = [messages] if messages.is_a?(Hash)
endpoint_path = '/bot/message/narrowcast'
payload = {
messages: messages,
recipient: recipient,
filter: filter,
limit: limit
}.to_json
post(endpoint, endpoint_path, payload, credentials)
end
def leave_group(group_id)
channel_token_required
endpoint_path = "/bot/group/#{group_id}/leave"
post(endpoint, endpoint_path, nil, credentials)
end
def leave_room(room_id)
channel_token_required
endpoint_path = "/bot/room/#{room_id}/leave"
post(endpoint, endpoint_path, nil, credentials)
end
# Get message content.
#
# @param identifier [String] Message's identifier
# @return [Net::HTTPResponse]
def get_message_content(identifier)
channel_token_required
endpoint_path = "/bot/message/#{identifier}/content"
get(blob_endpoint, endpoint_path, credentials)
end
# Get an user's profile.
#
# @param user_id [String] User Id user_id
# @return [Net::HTTPResponse]
def get_profile(user_id)
channel_token_required
endpoint_path = "/bot/profile/#{user_id}"
get(endpoint, endpoint_path, credentials)
end
# Get an user's profile of a group.
#
# @param group_id [String] Group's identifier
# @param user_id [String] User Id user_id
#
# @return [Net::HTTPResponse]
def get_group_member_profile(group_id, user_id)
channel_token_required
endpoint_path = "/bot/group/#{group_id}/member/#{user_id}"
get(endpoint, endpoint_path, credentials)
end
# Get an user's profile of a room.
#
# @param room_id [String] Room's identifier
# @param user_id [String] User Id user_id
#
# @return [Net::HTTPResponse]
def get_room_member_profile(room_id, user_id)
channel_token_required
endpoint_path = "/bot/room/#{room_id}/member/#{user_id}"
get(endpoint, endpoint_path, credentials)
end
# Get user IDs of a group
#
# @param group_id [String] Group's identifier
# @param continuation_token [String] Identifier to return next page
# (next property to be included in the response)
#
# @return [Net::HTTPResponse]
def get_group_member_ids(group_id, continuation_token = nil)
channel_token_required
endpoint_path = "/bot/group/#{group_id}/members/ids"
endpoint_path += "?start=#{continuation_token}" if continuation_token
get(endpoint, endpoint_path, credentials)
end
# Get user IDs of a room
#
# @param room_id [String] Room's identifier
# @param continuation_token [String] Identifier to return next page
# (next property to be included in the response)
#
# @return [Net::HTTPResponse]
def get_room_member_ids(room_id, continuation_token = nil)
channel_token_required
endpoint_path = "/bot/room/#{room_id}/members/ids"
endpoint_path += "?start=#{continuation_token}" if continuation_token
get(endpoint, endpoint_path, credentials)
end
# Get a list of all uploaded rich menus
#
# @return [Net::HTTPResponse]
def get_rich_menus
channel_token_required
endpoint_path = '/bot/richmenu/list'
get(endpoint, endpoint_path, credentials)
end
# Get a rich menu via a rich menu ID
#
# @param rich_menu_id [String] ID of an uploaded rich menu
#
# @return [Net::HTTPResponse]
def get_rich_menu(rich_menu_id)
channel_token_required
endpoint_path = "/bot/richmenu/#{rich_menu_id}"
get(endpoint, endpoint_path, credentials)
end
# Gets the number of messages sent with the /bot/message/reply endpoint.
#
# @param date [String] Date the messages were sent (format: yyyyMMdd)
#
# @return [Net::HTTPResponse]
def get_message_delivery_reply(date)
channel_token_required
endpoint_path = "/bot/message/delivery/reply?date=#{date}"
get(endpoint, endpoint_path, credentials)
end
# Gets the number of messages sent with the /bot/message/push endpoint.
#
# @param date [String] Date the messages were sent (format: yyyyMMdd)
#
# @return [Net::HTTPResponse]
def get_message_delivery_push(date)
channel_token_required
endpoint_path = "/bot/message/delivery/push?date=#{date}"
get(endpoint, endpoint_path, credentials)
end
# Gets the number of messages sent with the /bot/message/multicast endpoint.
#
# @param date [String] Date the messages were sent (format: yyyyMMdd)
#
# @return [Net::HTTPResponse]
def get_message_delivery_multicast(date)
channel_token_required
endpoint_path = "/bot/message/delivery/multicast?date=#{date}"
get(endpoint, endpoint_path, credentials)
end
# Gets the number of messages sent with the /bot/message/multicast endpoint.
#
# @param date [String] Date the messages were sent (format: yyyyMMdd)
#
# @return [Net::HTTPResponse]
def get_message_delivery_broadcast(date)
channel_token_required
endpoint_path = "/bot/message/delivery/broadcast?date=#{date}"
get(endpoint, endpoint_path, credentials)
end
# Create a rich menu
#
# @param rich_menu [Hash] The rich menu represented as a rich menu object
#
# @return [Net::HTTPResponse]
def create_rich_menu(rich_menu)
channel_token_required
endpoint_path = '/bot/richmenu'
post(endpoint, endpoint_path, rich_menu.to_json, credentials)
end
# Delete a rich menu
#
# @param rich_menu_id [String] ID of an uploaded rich menu
#
# @return [Net::HTTPResponse]
def delete_rich_menu(rich_menu_id)
channel_token_required
endpoint_path = "/bot/richmenu/#{rich_menu_id}"
delete(endpoint, endpoint_path, credentials)
end
# Get the ID of the rich menu linked to a user
#
# @param user_id [String] ID of the user
#
# @return [Net::HTTPResponse]
def get_user_rich_menu(user_id)
channel_token_required
endpoint_path = "/bot/user/#{user_id}/richmenu"
get(endpoint, endpoint_path, credentials)
end
# Get default rich menu
#
# @return [Net::HTTPResponse]
def get_default_rich_menu
channel_token_required
endpoint_path = '/bot/user/all/richmenu'
get(endpoint, endpoint_path, credentials)
end
# Set default rich menu (Link a rich menu to all user)
#
# @param rich_menu_id [String] ID of an uploaded rich menu
#
# @return [Net::HTTPResponse]
def set_default_rich_menu(rich_menu_id)
channel_token_required
endpoint_path = "/bot/user/all/richmenu/#{rich_menu_id}"
post(endpoint, endpoint_path, nil, credentials)
end
# Unset default rich menu (Unlink a rich menu from all user)
#
# @return [Net::HTTPResponse]
def unset_default_rich_menu
channel_token_required
endpoint_path = "/bot/user/all/richmenu"
delete(endpoint, endpoint_path, credentials)
end
# Link a rich menu to a user
#
# If you want to link a rich menu to multiple users,
# please consider to use bulk_link_rich_menus.
#
# @param user_id [String] ID of the user
# @param rich_menu_id [String] ID of an uploaded rich menu
#
# @return [Net::HTTPResponse]
def link_user_rich_menu(user_id, rich_menu_id)
channel_token_required
endpoint_path = "/bot/user/#{user_id}/richmenu/#{rich_menu_id}"
post(endpoint, endpoint_path, nil, credentials)
end
# Unlink a rich menu from a user
#
# @param user_id [String] ID of the user
#
# @return [Net::HTTPResponse]
def unlink_user_rich_menu(user_id)
channel_token_required
endpoint_path = "/bot/user/#{user_id}/richmenu"
delete(endpoint, endpoint_path, credentials)
end
# To link a rich menu to multiple users at a time
#
# @param user_ids [Array] ID of the user
# @param rich_menu_id [String] ID of the uploaded rich menu
#
# @return [Net::HTTPResponse]
def bulk_link_rich_menus(user_ids, rich_menu_id)
channel_token_required
endpoint_path = "/bot/richmenu/bulk/link"
post(endpoint, endpoint_path, { richMenuId: rich_menu_id, userIds: user_ids }.to_json, credentials)
end
# To unlink a rich menu from multiple users at a time
#
# @param user_ids [Array] ID of the user
#
# @return [Net::HTTPResponse]
def bulk_unlink_rich_menus(user_ids)
channel_token_required
endpoint_path = "/bot/richmenu/bulk/unlink"
post(endpoint, endpoint_path, { userIds: user_ids }.to_json, credentials)
end
# Download an image associated with a rich menu
#
# @param rich_menu_id [String] ID of an uploaded rich menu
#
# @return [Net::HTTPResponse]
def get_rich_menu_image(rich_menu_id)
channel_token_required
endpoint_path = "/bot/richmenu/#{rich_menu_id}/content"
get(blob_endpoint, endpoint_path, credentials)
end
# Upload and attaches an image to a rich menu
#
# @param rich_menu_id [String] The ID of the rich menu to attach the image to
# @param file [File] Image file to attach rich menu
#
# @return [Net::HTTPResponse]
def create_rich_menu_image(rich_menu_id, file)
channel_token_required
endpoint_path = "/bot/richmenu/#{rich_menu_id}/content"
headers = credentials.merge('Content-Type' => content_type(file))
post(blob_endpoint, endpoint_path, file.rewind && file.read, headers)
end
# Issue a link token to a user
#
# @param user_id [String] ID of the user
#
# @return [Net::HTTPResponse]
def create_link_token(user_id)
channel_token_required
endpoint_path = "/bot/user/#{user_id}/linkToken"
post(endpoint, endpoint_path, nil, credentials)
end
# Get the target limit for additional messages
#
# @return [Net::HTTPResponse]
def get_quota
channel_token_required
endpoint_path = "/bot/message/quota"
get(endpoint, endpoint_path, credentials)
end
# Get number of messages sent this month
#
# @return [Net::HTTPResponse]
def get_quota_consumption
channel_token_required
endpoint_path = "/bot/message/quota/consumption"
get(endpoint, endpoint_path, credentials)
end
# Returns the number of messages sent on a specified day
#
# @param [String] date (Format:yyyyMMdd, Example:20191231)
#
# @return [Net::HTTPResponse]
def get_number_of_message_deliveries(date)
channel_token_required
endpoint_path = "/bot/insight/message/delivery?date=#{date}"
get(endpoint, endpoint_path, credentials)
end
# Returns statistics about how users interact with narrowcast messages or broadcast messages sent from your LINE Official Account.
#
# @param [String] request_id
#
# @return [Net::HTTPResponse]
def get_user_interaction_statistics(request_id)
channel_token_required
endpoint_path = "/bot/insight/message/event?requestId=#{request_id}"
get(endpoint, endpoint_path, credentials)
end
# Returns the number of followers
#
# @param [String] date (Format:yyyyMMdd, Example:20191231)
#
# @return [Net::HTTPResponse]
def get_number_of_followers(date)
channel_token_required
endpoint_path = "/bot/insight/followers?date=#{date}"
get(endpoint, endpoint_path, credentials)
end
# Get the demographic attributes for a bot's friends.
#
# @return [Net::HTTPResponse]
def get_friend_demographics
channel_token_required
endpoint_path = '/bot/insight/demographic'
get(endpoint, endpoint_path, credentials)
end
# Fetch data, get content of specified URL.
#
# @param endpoint_base [String]
# @param endpoint_path [String]
# @param headers [Hash]
#
# @return [Net::HTTPResponse]
def get(endpoint_base, endpoint_path, headers = {})
headers = API::DEFAULT_HEADERS.merge(headers)
httpclient.get(endpoint_base + endpoint_path, headers)
end
# Post data, get content of specified URL.
#
# @param endpoint_base [String]
# @param endpoint_path [String]
# @param payload [String or NilClass]
# @param headers [Hash]
#
# @return [Net::HTTPResponse]
def post(endpoint_base, endpoint_path, payload = nil, headers = {})
headers = API::DEFAULT_HEADERS.merge(headers)
httpclient.post(endpoint_base + endpoint_path, payload, headers)
end
# Delete content of specified URL.
#
# @param endpoint_base [String]
# @param endpoint_path [String]
# @param headers [Hash]
#
# @return [Net::HTTPResponse]
def delete(endpoint_base, endpoint_path, headers = {})
headers = API::DEFAULT_HEADERS.merge(headers)
httpclient.delete(endpoint_base + endpoint_path, headers)
end
# Parse events from request.body
#
# @param request_body [String]
#
# @return [Array<Line::Bot::Event::Class>]
def parse_events_from(request_body)
json = JSON.parse(request_body)
json['events'].map do |item|
begin
klass = Event.const_get(Util.camelize(item['type']))
klass.new(item)
rescue NameError
Event::Base.new(item)
end
end
end
# Validate signature of a webhook event.
#
# https://developers.line.biz/en/reference/messaging-api/#signature-validation
#
# @param content [String] Request's body
# @param channel_signature [String] Request'header 'X-LINE-Signature' # HTTP_X_LINE_SIGNATURE
#
# @return [Boolean]
def validate_signature(content, channel_signature)
return false if !channel_signature || !channel_secret
hash = OpenSSL::HMAC.digest(OpenSSL::Digest::SHA256.new, channel_secret, content)
signature = Base64.strict_encode64(hash)
variable_secure_compare(channel_signature, signature)
end
private
# Constant time string comparison.
#
# via timing attacks.
# reference: https://github.com/rails/rails/blob/master/activesupport/lib/active_support/security_utils.rb
# @return [Boolean]
def variable_secure_compare(a, b)
secure_compare(::Digest::SHA256.hexdigest(a), ::Digest::SHA256.hexdigest(b))
end
# @return [Boolean]
def secure_compare(a, b)
return false unless a.bytesize == b.bytesize
l = a.unpack "C#{a.bytesize}"
res = 0
b.each_byte { |byte| res |= byte ^ l.shift }
res == 0
end
def content_type(file)
if file.respond_to?(:content_type)
content_type = file.content_type
raise ArgumentError, "invalid content type: #{content_type}" unless ['image/jpeg', 'image/png'].include?(content_type)
content_type
else
case file.path
when /\.jpe?g\z/i then 'image/jpeg'
when /\.png\z/i then 'image/png'
else
raise ArgumentError, "invalid file extension: #{file.path}"
end
end
end
def channel_token_required
raise ArgumentError, '`channel_token` is not configured' unless channel_token
end
def channel_id_required
raise ArgumentError, '`channel_id` is not configured' unless channel_id
end
def channel_secret_required
raise ArgumentError, '`channel_secret` is not configured' unless channel_secret
end
end
end
end
| 31.370112 | 136 | 0.626553 |
f7bcd3e9f99093425857af8eb7458d220878c01d | 325 | describe MiqAeMethodService::MiqAeServiceStorage do
let(:storage) { FactoryGirl.create(:storage) }
let(:svc_storage) { MiqAeMethodService::MiqAeServiceStorage.find(storage.id) }
it "#show_url" do
ui_url = stub_remote_ui_url
expect(svc_storage.show_url).to eq("#{ui_url}/storage/show/#{storage.id}")
end
end
| 29.545455 | 80 | 0.744615 |
87c01ef6c402c75e65ae80e2f184b9f0a9f1649c | 204 | # frozen_string_literal: true
class Location
include Mongoid::Document
field :name
field :info, type: Hash
field :occupants, type: Array
field :number, type: Integer
embedded_in :address
end
| 18.545455 | 31 | 0.745098 |
d50bd76d3c6d4f4d55e18ea3f6908769f89985a8 | 496 | # Be sure to restart your server when you modify this file.
# Your secret key for verifying the integrity of signed cookies.
# If you change this key, all old signed cookies will become invalid!
# Make sure the secret is at least 30 characters and all random,
# no regular words or you'll be exposed to dictionary attacks.
Dummy::Application.config.secret_token = 'cf498940d07d01054c9a39040adf052c907947f1738ee56460d31f5d03a955d7f13f7fa0db0b87a28778aa5b8cfeee6a44a889c3923455e98e73e3c3f57db537'
| 62 | 171 | 0.832661 |
62a7e5f40a6e09f66e5b9bbc6487993bd0a1422b | 381 | require 'forwardable'
class Faraday::CLI::MiddlewareFetcher::Container
#TODO: remove support for adapter set
extend Forwardable
def_delegators :@builder, :use, :request, :response, :adapter
def initialize(builder)
@builder = builder
end
def merge!(file_path)
Dir.chdir(File.dirname(file_path)) do
instance_eval(File.read(file_path))
end
end
end
| 20.052632 | 63 | 0.721785 |
087ce09dd74cc2e1d3d124f9b947dbf6c0c0e49c | 881 | require 'hiptest-publisher/nodes'
module Hiptest
module GherkinAddon
def walk_call(call)
if call.free_text_arg
@rendered_children[:free_text_arg] = rendered_freetext_arg(call)
end
if call.datatable_arg
@rendered_children[:datatable_arg] = rendered_datatable_arg(call)
end
super(call)
end
def walk_folder(folder)
@rendered_children[:ancestor_tags] = ancestor_tags(folder)
super(folder)
end
private
def rendered_datatable_arg(call)
@rendered[call.datatable_arg.children[:value]]
end
def rendered_freetext_arg(call)
@rendered[call.free_text_arg.children[:value]]
end
def ancestor_tags(folder)
ancestor_tags = folder.ancestors.map { |f| f.children[:tags] }.flatten.uniq
ancestor_tags.map { |t| Hiptest::Renderer.render(t, @context) }
end
end
end
| 22.589744 | 81 | 0.685585 |
38884222d08edd83bddb3de652ea025a6144c661 | 16,612 | require "dev-cmd/audit"
require "formulary"
module Count
def self.increment
@count ||= 0
@count += 1
end
end
describe FormulaText do
alias_matcher :have_data, :be_data
alias_matcher :have_end, :be_end
alias_matcher :have_trailing_newline, :be_trailing_newline
let(:dir) { mktmpdir }
def formula_text(name, body = nil, options = {})
path = dir/"#{name}.rb"
path.write <<~EOS
class #{Formulary.class_s(name)} < Formula
#{body}
end
#{options[:patch]}
EOS
described_class.new(path)
end
specify "simple valid Formula" do
ft = formula_text "valid", <<~EOS
url "http://www.example.com/valid-1.0.tar.gz"
EOS
expect(ft).not_to have_data
expect(ft).not_to have_end
expect(ft).to have_trailing_newline
expect(ft =~ /\burl\b/).to be_truthy
expect(ft.line_number(/desc/)).to be nil
expect(ft.line_number(/\burl\b/)).to eq(2)
expect(ft).to include("Valid")
end
specify "#trailing_newline?" do
ft = formula_text "newline"
expect(ft).to have_trailing_newline
end
specify "#data?" do
ft = formula_text "data", <<~EOS
patch :DATA
EOS
expect(ft).to have_data
end
specify "#end?" do
ft = formula_text "end", "", patch: "__END__\na patch here"
expect(ft).to have_end
expect(ft.without_patch).to eq("class End < Formula\n \nend")
end
end
describe FormulaAuditor do
def formula_auditor(name, text, options = {})
path = Pathname.new "#{dir}/#{name}.rb"
path.open("w") do |f|
f.write text
end
described_class.new(Formulary.factory(path), options)
end
let(:dir) { mktmpdir }
describe "#problems" do
it "is empty by default" do
fa = formula_auditor "foo", <<~EOS
class Foo < Formula
url "http://example.com/foo-1.0.tgz"
end
EOS
expect(fa.problems).to be_empty
end
end
describe "#audit_file" do
specify "file permissions" do
allow(File).to receive(:umask).and_return(022)
fa = formula_auditor "foo", <<~EOS
class Foo < Formula
url "http://example.com/foo-1.0.tgz"
end
EOS
path = fa.formula.path
path.chmod 0400
fa.audit_file
expect(fa.problems)
.to eq(["Incorrect file permissions (400): chmod 644 #{path}"])
end
specify "DATA but no __END__" do
fa = formula_auditor "foo", <<~EOS
class Foo < Formula
url "http://example.com/foo-1.0.tgz"
patch :DATA
end
EOS
fa.audit_file
expect(fa.problems).to eq(["'DATA' was found, but no '__END__'"])
end
specify "__END__ but no DATA" do
fa = formula_auditor "foo", <<~EOS
class Foo < Formula
url "http://example.com/foo-1.0.tgz"
end
__END__
a patch goes here
EOS
fa.audit_file
expect(fa.problems).to eq(["'__END__' was found, but 'DATA' is not used"])
end
specify "no trailing newline" do
fa = formula_auditor "foo", 'class Foo<Formula; url "file:///foo-1.0.tgz";end'
fa.audit_file
expect(fa.problems).to eq(["File should end with a newline"])
end
specify "no issue" do
fa = formula_auditor "foo", <<~EOS
class Foo < Formula
url "http://example.com/foo-1.0.tgz"
homepage "http://example.com"
end
EOS
fa.audit_file
expect(fa.problems).to eq([])
end
end
describe "#line_problems" do
specify "pkgshare" do
fa = formula_auditor "foo", <<~EOS, strict: true
class Foo < Formula
url "http://example.com/foo-1.0.tgz"
end
EOS
fa.line_problems 'ohai "#{share}/foo"', 3
expect(fa.problems.shift).to eq("Use \#{pkgshare} instead of \#{share}/foo")
fa.line_problems 'ohai "#{share}/foo/bar"', 3
expect(fa.problems.shift).to eq("Use \#{pkgshare} instead of \#{share}/foo")
fa.line_problems 'ohai share/"foo"', 3
expect(fa.problems.shift).to eq('Use pkgshare instead of (share/"foo")')
fa.line_problems 'ohai share/"foo/bar"', 3
expect(fa.problems.shift).to eq('Use pkgshare instead of (share/"foo")')
fa.line_problems 'ohai "#{share}/foo-bar"', 3
expect(fa.problems).to eq([])
fa.line_problems 'ohai share/"foo-bar"', 3
expect(fa.problems).to eq([])
fa.line_problems 'ohai share/"bar"', 3
expect(fa.problems).to eq([])
end
# Regression test for https://github.com/Homebrew/legacy-homebrew/pull/48744
# Formulae with "++" in their name would break various audit regexps:
# Error: nested *?+ in regexp: /^libxml++3\s/
specify "++ in name" do
fa = formula_auditor "foolibc++", <<~EOS, strict: true
class Foolibcxx < Formula
desc "foolibc++ is a test"
url "http://example.com/foo-1.0.tgz"
end
EOS
fa.line_problems 'ohai "#{share}/foolibc++"', 3
expect(fa.problems.shift)
.to eq("Use \#{pkgshare} instead of \#{share}/foolibc++")
fa.line_problems 'ohai share/"foolibc++"', 3
expect(fa.problems.shift)
.to eq('Use pkgshare instead of (share/"foolibc++")')
end
end
describe "#audit_github_repository" do
specify "#audit_github_repository when HOMEBREW_NO_GITHUB_API is set" do
ENV["HOMEBREW_NO_GITHUB_API"] = "1"
fa = formula_auditor "foo", <<~EOS, strict: true, online: true
class Foo < Formula
homepage "https://github.com/example/example"
url "http://example.com/foo-1.0.tgz"
end
EOS
fa.audit_github_repository
expect(fa.problems).to eq([])
end
end
describe "#audit_deps" do
describe "a dependency on a macOS-provided keg-only formula" do
describe "which is whitelisted" do
let(:fa) do
formula_auditor "foo", <<~EOS, new_formula: true
class Foo < Formula
url "http://example.com/foo-1.0.tgz"
homepage "http://example.com"
depends_on "openssl"
end
EOS
end
let(:f_openssl) do
formula do
url "http://example.com/openssl-1.0.tgz"
homepage "http://example.com"
keg_only :provided_by_macos
end
end
before do
allow(fa.formula.deps.first)
.to receive(:to_formula).and_return(f_openssl)
fa.audit_deps
end
subject { fa }
its(:problems) { are_expected.to be_empty }
end
describe "which is not whitelisted" do
let(:fa) do
formula_auditor "foo", <<~EOS, new_formula: true
class Foo < Formula
url "http://example.com/foo-1.0.tgz"
homepage "http://example.com"
depends_on "bc"
end
EOS
end
let(:f_bc) do
formula do
url "http://example.com/bc-1.0.tgz"
homepage "http://example.com"
keg_only :provided_by_macos
end
end
before do
allow(fa.formula.deps.first)
.to receive(:to_formula).and_return(f_bc)
fa.audit_deps
end
subject { fa }
its(:problems) { are_expected.to match([/unnecessary/]) }
end
end
end
describe "#audit_keg_only_style" do
specify "keg_only_needs_downcasing" do
fa = formula_auditor "foo", <<~EOS, strict: true
class Foo < Formula
url "http://example.com/foo-1.0.tgz"
keg_only "Because why not"
end
EOS
fa.audit_keg_only_style
expect(fa.problems)
.to eq(["'Because' from the keg_only reason should be 'because'.\n"])
end
specify "keg_only_redundant_period" do
fa = formula_auditor "foo", <<~EOS, strict: true
class Foo < Formula
url "http://example.com/foo-1.0.tgz"
keg_only "because this line ends in a period."
end
EOS
fa.audit_keg_only_style
expect(fa.problems)
.to eq(["keg_only reason should not end with a period."])
end
specify "keg_only_handles_block_correctly" do
fa = formula_auditor "foo", <<~EOS, strict: true
class Foo < Formula
url "http://example.com/foo-1.0.tgz"
keg_only <<~EOF
this line starts with a lowercase word.
This line does not but that shouldn't be a
problem
EOF
end
EOS
fa.audit_keg_only_style
expect(fa.problems)
.to eq([])
end
specify "keg_only_handles_whitelist_correctly" do
fa = formula_auditor "foo", <<~EOS, strict: true
class Foo < Formula
url "http://example.com/foo-1.0.tgz"
keg_only "Apple ships foo in the CLT package"
end
EOS
fa.audit_keg_only_style
expect(fa.problems)
.to eq([])
end
end
describe "#audit_revision_and_version_scheme" do
let(:origin_tap_path) { Tap::TAP_DIRECTORY/"homebrew/homebrew-foo" }
let(:formula_subpath) { "Formula/foo#{@foo_version}.rb" }
let(:origin_formula_path) { origin_tap_path/formula_subpath }
let(:tap_path) { Tap::TAP_DIRECTORY/"homebrew/homebrew-bar" }
let(:formula_path) { tap_path/formula_subpath }
before(:each) do
@foo_version = Count.increment
origin_formula_path.write <<~EOS
class Foo#{@foo_version} < Formula
url "https://example.com/foo-1.0.tar.gz"
revision 2
version_scheme 1
end
EOS
origin_tap_path.mkpath
origin_tap_path.cd do
system "git", "init"
system "git", "add", "--all"
system "git", "commit", "-m", "init"
end
tap_path.mkpath
tap_path.cd do
system "git", "clone", origin_tap_path, "."
end
end
subject do
fa = described_class.new(Formulary.factory(formula_path))
fa.audit_revision_and_version_scheme
fa.problems.first
end
def formula_gsub(before, after = "")
text = formula_path.read
text.gsub! before, after
formula_path.unlink
formula_path.write text
end
def formula_gsub_commit(before, after = "")
text = origin_formula_path.read
text.gsub!(before, after)
origin_formula_path.unlink
origin_formula_path.write text
origin_tap_path.cd do
system "git", "commit", "-am", "commit"
end
tap_path.cd do
system "git", "fetch"
system "git", "reset", "--hard", "origin/master"
end
end
context "revisions" do
context "should not be removed when first committed above 0" do
it { is_expected.to be_nil }
end
context "should not decrease with the same version" do
before { formula_gsub_commit "revision 2", "revision 1" }
it { is_expected.to match("revision should not decrease (from 2 to 1)") }
end
context "should not be removed with the same version" do
before { formula_gsub_commit "revision 2" }
it { is_expected.to match("revision should not decrease (from 2 to 0)") }
end
context "should not decrease with the same, uncommitted version" do
before { formula_gsub "revision 2", "revision 1" }
it { is_expected.to match("revision should not decrease (from 2 to 1)") }
end
context "should be removed with a newer version" do
before { formula_gsub_commit "foo-1.0.tar.gz", "foo-1.1.tar.gz" }
it { is_expected.to match("'revision 2' should be removed") }
end
context "should not warn on an newer version revision removal" do
before do
formula_gsub_commit "revision 2", ""
formula_gsub_commit "foo-1.0.tar.gz", "foo-1.1.tar.gz"
end
it { is_expected.to be_nil }
end
context "should only increment by 1 with an uncommitted version" do
before do
formula_gsub "foo-1.0.tar.gz", "foo-1.1.tar.gz"
formula_gsub "revision 2", "revision 4"
end
it { is_expected.to match("revisions should only increment by 1") }
end
context "should not warn on past increment by more than 1" do
before do
formula_gsub_commit "revision 2", "# no revision"
formula_gsub_commit "foo-1.0.tar.gz", "foo-1.1.tar.gz"
formula_gsub_commit "# no revision", "revision 3"
end
it { is_expected.to be_nil }
end
end
context "version_schemes" do
context "should not decrease with the same version" do
before { formula_gsub_commit "version_scheme 1" }
it { is_expected.to match("version_scheme should not decrease (from 1 to 0)") }
end
context "should not decrease with a new version" do
before do
formula_gsub_commit "foo-1.0.tar.gz", "foo-1.1.tar.gz"
formula_gsub_commit "version_scheme 1", ""
formula_gsub_commit "revision 2", ""
end
it { is_expected.to match("version_scheme should not decrease (from 1 to 0)") }
end
context "should only increment by 1" do
before do
formula_gsub_commit "version_scheme 1", "# no version_scheme"
formula_gsub_commit "foo-1.0.tar.gz", "foo-1.1.tar.gz"
formula_gsub_commit "revision 2", ""
formula_gsub_commit "# no version_scheme", "version_scheme 3"
end
it { is_expected.to match("version_schemes should only increment by 1") }
end
end
context "versions" do
context "uncommitted should not decrease" do
before { formula_gsub "foo-1.0.tar.gz", "foo-0.9.tar.gz" }
it { is_expected.to match("stable version should not decrease (from 1.0 to 0.9)") }
end
context "committed can decrease" do
before do
formula_gsub_commit "revision 2"
formula_gsub_commit "foo-1.0.tar.gz", "foo-0.9.tar.gz"
end
it { is_expected.to be_nil }
end
context "can decrease with version_scheme increased" do
before do
formula_gsub "revision 2"
formula_gsub "foo-1.0.tar.gz", "foo-0.9.tar.gz"
formula_gsub "version_scheme 1", "version_scheme 2"
end
it { is_expected.to be_nil }
end
end
end
describe "#audit_url_is_not_binary" do
specify "it detects a url containing darwin and x86_64" do
fa = formula_auditor "foo", <<~EOS, official_tap: true
class Foo < Formula
url "https://example.com/example-darwin.x86_64.tar.gz"
end
EOS
fa.audit_url_is_not_binary
expect(fa.problems.first)
.to match("looks like a binary package, not a source archive. Official taps are source-only.")
end
specify "it detects a url containing darwin and amd64" do
fa = formula_auditor "foo", <<~EOS, official_tap: true
class Foo < Formula
url "https://example.com/example-darwin.amd64.tar.gz"
end
EOS
fa.audit_url_is_not_binary
expect(fa.problems.first)
.to match("looks like a binary package, not a source archive. Official taps are source-only.")
end
specify "it works on the devel spec" do
fa = formula_auditor "foo", <<~EOS, official_tap: true
class Foo < Formula
url "https://example.com/valid-1.0.tar.gz"
devel do
url "https://example.com/example-darwin.x86_64.tar.gz"
end
end
EOS
fa.audit_url_is_not_binary
expect(fa.problems.first)
.to match("looks like a binary package, not a source archive. Official taps are source-only.")
end
specify "it works on the head spec" do
fa = formula_auditor "foo", <<~EOS, official_tap: true
class Foo < Formula
url "https://example.com/valid-1.0.tar.gz"
head do
url "https://example.com/example-darwin.x86_64.tar.gz"
end
end
EOS
fa.audit_url_is_not_binary
expect(fa.problems.first)
.to match("looks like a binary package, not a source archive. Official taps are source-only.")
end
specify "it ignores resource urls" do
fa = formula_auditor "foo", <<~EOS, official_tap: true
class Foo < Formula
url "https://example.com/valid-1.0.tar.gz"
resource "binary_res" do
url "https://example.com/example-darwin.x86_64.tar.gz"
end
end
EOS
fa.audit_url_is_not_binary
expect(fa.problems).to eq([])
end
end
end
| 27.503311 | 102 | 0.599928 |
f7295efe73abec5524d5d32e84378ad38654c6ad | 474 | # frozen_string_literal: true
describe ProcessDecisionDocumentJob do
context ".perform" do
subject { ProcessDecisionDocumentJob.perform_now(decision_document.id) }
let(:decision_document) { build_stubbed(:decision_document) }
it "processes the decision document" do
allow(DecisionDocument).to receive(:find).with(decision_document.id).and_return(decision_document)
expect(decision_document).to receive(:process!)
subject
end
end
end
| 29.625 | 104 | 0.761603 |
91b961716cd106139d4e28cda345646488651e3a | 278 | class CreateProyectosUsersJoinTable < ActiveRecord::Migration
def change
create_table :proyectos_users, id: false do |t|
t.integer :id_proyecto
t.integer :id_user
end
add_index :proyectos_users, :id_proyecto
add_index :proyectos_users, :id_user
end
end
| 23.166667 | 61 | 0.755396 |
6a3a47df9bacddcaf15a7baaaf47ecd5299fabd0 | 2,721 | # This file is copied to spec/ when you run 'rails generate rspec:install'
require 'spec_helper'
ENV['RAILS_ENV'] ||= 'test'
require File.expand_path('../../config/environment', __FILE__)
# Prevent database truncation if the environment is production
abort("The Rails environment is running in production mode!") if Rails.env.production?
require 'rspec/rails'
# Add additional requires below this line. Rails is not loaded until this point!
# Requires supporting ruby files with custom matchers and macros, etc, in
# spec/support/ and its subdirectories. Files matching `spec/**/*_spec.rb` are
# run as spec files by default. This means that files in spec/support that end
# in _spec.rb will both be required and run as specs, causing the specs to be
# run twice. It is recommended that you do not name files matching this glob to
# end with _spec.rb. You can configure this pattern with the --pattern
# option on the command line or in ~/.rspec, .rspec or `.rspec-local`.
#
# The following line is provided for convenience purposes. It has the downside
# of increasing the boot-up time by auto-requiring all files in the support
# directory. Alternatively, in the individual `*_spec.rb` files, manually
# require only the support files necessary.
#
Dir[Rails.root.join('spec/support/**/*.rb')].each { |f| require f }
# Checks for pending migrations and applies them before tests are run.
# If you are not using ActiveRecord, you can remove this line.
ActiveRecord::Migration.maintain_test_schema!
RSpec.configure do |config|
# Remove this line if you're not using ActiveRecord or ActiveRecord fixtures
# config.fixture_path = "#{::Rails.root}/spec/fixtures"
config.include FactoryBot::Syntax::Methods
# If you're not using ActiveRecord, or you'd prefer not to run each of your
# examples within a transaction, remove the following line or assign false
# instead of true.
config.use_transactional_fixtures = true
# RSpec Rails can automatically mix in different behaviours to your tests
# based on their file location, for example enabling you to call `get` and
# `post` in specs under `spec/controllers`.
#
# You can disable this behaviour by removing the line below, and instead
# explicitly tag your specs with their type, e.g.:
#
# RSpec.describe UsersController, :type => :controller do
# # ...
# end
#
# The different available types are documented in the features, such as in
# https://relishapp.com/rspec/rspec-rails/docs
config.infer_spec_type_from_file_location!
# Filter lines from Rails gems in backtraces.
config.filter_rails_from_backtrace!
# arbitrary gems may also be filtered via:
# config.filter_gems_from_backtrace("gem name")
end
| 45.35 | 86 | 0.751194 |
2621a66970ae42ebabffaa6a08cdcb689917197e | 16,026 | # -*- coding: binary -*-
require 'tempfile'
require 'rex/post/meterpreter'
module Rex
module Post
module Meterpreter
module Ui
###
#
# The file system portion of the standard API extension.
#
###
class Console::CommandDispatcher::Stdapi::Fs
Klass = Console::CommandDispatcher::Stdapi::Fs
include Console::CommandDispatcher
#
# Options for the download command.
#
@@download_opts = Rex::Parser::Arguments.new(
"-h" => [ false, "Help banner." ],
"-r" => [ false, "Download recursively." ])
#
# Options for the upload command.
#
@@upload_opts = Rex::Parser::Arguments.new(
"-h" => [ false, "Help banner." ],
"-r" => [ false, "Upload recursively." ])
#
# List of supported commands.
#
def commands
all = {
"cat" => "Read the contents of a file to the screen",
"cd" => "Change directory",
"del" => "Delete the specified file",
"download" => "Download a file or directory",
"edit" => "Edit a file",
"getlwd" => "Print local working directory",
"getwd" => "Print working directory",
"lcd" => "Change local working directory",
"lpwd" => "Print local working directory",
"ls" => "List files",
"mkdir" => "Make directory",
"pwd" => "Print working directory",
"rm" => "Delete the specified file",
"mv" => "Move source to destination",
"rmdir" => "Remove directory",
"search" => "Search for files",
"upload" => "Upload a file or directory",
}
reqs = {
"cat" => [ ],
"cd" => [ "stdapi_fs_chdir" ],
"del" => [ "stdapi_fs_rm" ],
"download" => [ ],
"edit" => [ ],
"getlwd" => [ ],
"getwd" => [ "stdapi_fs_getwd" ],
"lcd" => [ ],
"lpwd" => [ ],
"ls" => [ "stdapi_fs_stat", "stdapi_fs_ls" ],
"mkdir" => [ "stdapi_fs_mkdir" ],
"pwd" => [ "stdapi_fs_getwd" ],
"rmdir" => [ "stdapi_fs_delete_dir" ],
"rm" => [ "stdapi_fs_delete_file" ],
"mv" => [ "stdapi_fs_file_move" ],
"search" => [ "stdapi_fs_search" ],
"upload" => [ ],
}
all.delete_if do |cmd, desc|
del = false
reqs[cmd].each do |req|
next if client.commands.include? req
del = true
break
end
del
end
all
end
#
# Name for this dispatcher.
#
def name
"Stdapi: File system"
end
#
# Search for files.
#
def cmd_search(*args)
root = nil
glob = nil
recurse = true
opts = Rex::Parser::Arguments.new(
"-h" => [ false, "Help Banner." ],
"-d" => [ true, "The directory/drive to begin searching from. Leave empty to search all drives. (Default: #{root})" ],
"-f" => [ true, "The file pattern glob to search for. (e.g. *secret*.doc?)" ],
"-r" => [ true, "Recursivly search sub directories. (Default: #{recurse})" ]
)
opts.parse(args) { | opt, idx, val |
case opt
when "-h"
print_line("Usage: search [-d dir] [-r recurse] -f pattern")
print_line("Search for files.")
print_line(opts.usage)
return
when "-d"
root = val
when "-f"
glob = val
when "-r"
recurse = false if val =~ /^(f|n|0)/i
end
}
if not glob
print_error("You must specify a valid file glob to search for, e.g. >search -f *.doc")
return
end
files = client.fs.file.search(root, glob, recurse)
if not files.empty?
print_line("Found #{files.length} result#{ files.length > 1 ? 's' : '' }...")
files.each do | file |
if file['size'] > 0
print(" #{file['path']}#{ file['path'].empty? ? '' : '\\' }#{file['name']} (#{file['size']} bytes)\n")
else
print(" #{file['path']}#{ file['path'].empty? ? '' : '\\' }#{file['name']}\n")
end
end
else
print_line("No files matching your search were found.")
end
end
#
# Reads the contents of a file and prints them to the screen.
#
def cmd_cat(*args)
if (args.length == 0)
print_line("Usage: cat file")
return true
end
if (client.fs.file.stat(args[0]).directory?)
print_error("#{args[0]} is a directory")
else
fd = client.fs.file.new(args[0], "rb")
begin
until fd.eof?
print(fd.read)
end
# EOFError is raised if file is empty, do nothing, just catch
rescue EOFError
end
fd.close
end
true
end
#
# Change the working directory.
#
def cmd_cd(*args)
if (args.length == 0)
print_line("Usage: cd directory")
return true
end
if args[0] =~ /\%(\w*)\%/
client.fs.dir.chdir(client.fs.file.expand_path(args[0].upcase))
else
client.fs.dir.chdir(args[0])
end
return true
end
#
# Change the local working directory.
#
def cmd_lcd(*args)
if (args.length == 0)
print_line("Usage: lcd directory")
return true
end
::Dir.chdir(args[0])
return true
end
#
# Delete the specified file.
#
def cmd_rm(*args)
if (args.length == 0)
print_line("Usage: rm file")
return true
end
client.fs.file.rm(args[0])
return true
end
alias :cmd_del :cmd_rm
#
# Move source to destination
#
def cmd_mv(*args)
if (args.length < 2)
print_line("Usage: mv oldfile newfile")
return true
end
client.fs.file.mv(args[0],args[1])
return true
end
alias :cmd_move :cmd_mv
alias :cmd_rename :cmd_mv
def cmd_download_help
print_line("Usage: download [options] src1 src2 src3 ... destination")
print_line
print_line("Downloads remote files and directories to the local machine.")
print_line(@@download_opts.usage)
end
#
# Downloads a file or directory from the remote machine to the local
# machine.
#
def cmd_download(*args)
if (args.empty? or args.include? "-h")
cmd_download_help
return true
end
recursive = false
src_items = []
last = nil
dest = nil
@@download_opts.parse(args) { |opt, idx, val|
case opt
when "-r"
recursive = true
when nil
src_items << last if (last)
last = val
end
}
# No files given, nothing to do
if not last
cmd_download_help
return true
end
# Source and destination will be the same
if src_items.empty?
src_items << last
# Use the basename of the remote filename so we don't end up with
# a file named c:\\boot.ini in linux
dest = ::Rex::Post::Meterpreter::Extensions::Stdapi::Fs::File.basename(last)
else
dest = last
end
# Download to a directory, not a pattern
if client.fs.file.is_glob?(dest)
dest = ::File.dirname(dest)
end
# Go through each source item and download them
src_items.each { |src|
glob = nil
if client.fs.file.is_glob?(src)
glob = ::File.basename(src)
src = ::File.dirname(src)
end
# Use search if possible for recursive pattern matching. It will work
# more intuitively since it will not try to match on intermediate
# directories, only file names.
if glob && recursive && client.commands.include?('stdapi_fs_search')
files = client.fs.file.search(src, glob, recursive)
if !files.empty?
print_line("Downloading #{files.length} file#{files.length > 1 ? 's' : ''}...")
files.each do |file|
src_separator = client.fs.file.separator
src_path = file['path'] + client.fs.file.separator + file['name']
dest_path = src_path.tr(src_separator, ::File::SEPARATOR)
client.fs.file.download(dest_path, src_path) do |step, src, dst|
puts step
print_status("#{step.ljust(11)}: #{src} -> #{dst}")
client.framework.events.on_session_download(client, src, dest) if msf_loaded?
end
end
else
print_status("No matching files found for download")
end
else
# Perform direct matching
stat = client.fs.file.stat(src)
if (stat.directory?)
client.fs.dir.download(dest, src, recursive, true, glob) do |step, src, dst|
print_status("#{step.ljust(11)}: #{src} -> #{dst}")
client.framework.events.on_session_download(client, src, dest) if msf_loaded?
end
elsif (stat.file?)
client.fs.file.download(dest, src) do |step, src, dst|
print_status("#{step.ljust(11)}: #{src} -> #{dst}")
client.framework.events.on_session_download(client, src, dest) if msf_loaded?
end
end
end
}
true
end
#
# Downloads a file to a temporary file, spawns and editor, and then uploads
# the contents to the remote machine after completion.
#
def cmd_edit(*args)
if (args.length == 0)
print_line("Usage: edit file")
return true
end
# Get a temporary file path
meterp_temp = Tempfile.new('meterp')
meterp_temp.binmode
temp_path = meterp_temp.path
# Try to download the file, but don't worry if it doesn't exist
client.fs.file.download_file(temp_path, args[0]) rescue nil
# Spawn the editor (default to vi)
editor = Rex::Compat.getenv('EDITOR') || 'vi'
# If it succeeds, upload it to the remote side.
if (system("#{editor} #{temp_path}") == true)
client.fs.file.upload_file(args[0], temp_path)
end
# Get rid of that pesky temporary file
::File.delete(temp_path) rescue nil
end
#
# Display the local working directory.
#
def cmd_lpwd(*args)
print_line(::Dir.pwd)
return true
end
alias cmd_getlwd cmd_lpwd
def list_path(path, columns, sort, order, short, recursive = false, depth = 0)
# avoid infinite recursion
if depth > 100
return
end
tbl = Rex::Ui::Text::Table.new(
'Header' => "Listing: #{path}",
'SortIndex' => columns.index(sort),
'SortOrder' => order,
'Columns' => columns)
items = 0
# Enumerate each item...
# No need to sort as Table will do it for us
client.fs.dir.entries_with_info(path).each do |p|
ffstat = p['StatBuf']
fname = p['FileName'] || 'unknown'
row = [
ffstat ? ffstat.prettymode : '',
ffstat ? ffstat.size : '',
ffstat ? ffstat.ftype[0,3] : '',
ffstat ? ffstat.mtime : '',
fname
]
row.insert(4, p['FileShortName'] || '') if short
if fname != '.' && fname != '..'
tbl << row
items += 1
if recursive && ffstat && ffstat.directory?
if client.fs.file.is_glob?(path)
child_path = ::File.dirname(path) + ::File::SEPARATOR + fname
child_path += ::File::SEPARATOR + ::File.basename(path)
else
child_path = path + ::File::SEPARATOR + fname
end
begin
list_path(child_path, columns, sort, order, short, recursive, depth + 1)
rescue RequestError
end
end
end
end
if items > 0
print_line(tbl.to_s)
else
print_line("No entries exist in #{path}")
end
end
#
# Lists files
#
def cmd_ls(*args)
# Check sort column
sort = args.include?('-S') ? 'Size' : 'Name'
sort = args.include?('-t') ? 'Last modified' : sort
args.delete('-S')
args.delete('-t')
# Check whether to include the short name option
short = args.include?('-x')
args.delete('-x')
# Check sort order
order = args.include?('-r') ? :reverse : :forward
args.delete('-r')
# Check for recursive mode
recursive = !args.delete('-R').nil?
args.delete('-l')
# Check for cries of help
if args.length > 1 || args.any? { |a| a[0] == '-' }
print_line('Usage: ls [dir] [-x] [-S] [-t] [-r]')
print_line(' -x Show short file names')
print_line(' -S Sort by size')
print_line(' -t Sort by time modified')
print_line(' -r Reverse sort order')
print_line(' -l List in long format (default)')
print_line(' -R Recursively list subdirectories encountered.')
return true
end
path = args[0] || client.fs.dir.getwd
columns = [ 'Mode', 'Size', 'Type', 'Last modified', 'Name' ]
columns.insert(4, 'Short Name') if short
stat_path = path
# Check session capabilities
is_glob = client.fs.file.is_glob?(path)
if is_glob
if !client.commands.include?('stdapi_fs_search')
print_line('File globbing not supported with this session')
return
end
stat_path = ::File.dirname(path)
end
stat = client.fs.file.stat(stat_path)
if stat.directory?
list_path(path, columns, sort, order, short, recursive)
else
print_line("#{stat.prettymode} #{stat.size} #{stat.ftype[0,3]} #{stat.mtime} #{path}")
end
return true
end
#
# Make one or more directory.
#
def cmd_mkdir(*args)
if (args.length == 0)
print_line("Usage: mkdir dir1 dir2 dir3 ...")
return true
end
args.each { |dir|
print_line("Creating directory: #{dir}")
client.fs.dir.mkdir(dir)
}
return true
end
#
# Display the working directory.
#
def cmd_pwd(*args)
print_line(client.fs.dir.getwd)
end
alias cmd_getwd cmd_pwd
#
# Removes one or more directory if it's empty.
#
def cmd_rmdir(*args)
if (args.length == 0 or args.include?("-h"))
print_line("Usage: rmdir dir1 dir2 dir3 ...")
return true
end
args.each { |dir|
print_line("Removing directory: #{dir}")
client.fs.dir.rmdir(dir)
}
return true
end
def cmd_upload_help
print_line("Usage: upload [options] src1 src2 src3 ... destination")
print_line
print_line("Uploads local files and directories to the remote machine.")
print_line(@@upload_opts.usage)
end
#
# Uploads a file or directory to the remote machine from the local
# machine.
#
def cmd_upload(*args)
if (args.empty? or args.include?("-h"))
cmd_upload_help
return true
end
recursive = false
src_items = []
last = nil
dest = nil
@@upload_opts.parse(args) { |opt, idx, val|
case opt
when "-r"
recursive = true
when nil
if (last)
src_items << last
end
last = val
end
}
return true if not last
# Source and destination will be the same
src_items << last if src_items.empty?
dest = last
# Go through each source item and upload them
src_items.each { |src|
stat = ::File.stat(src)
if (stat.directory?)
client.fs.dir.upload(dest, src, recursive) { |step, src, dst|
print_status("#{step.ljust(11)}: #{src} -> #{dst}")
client.framework.events.on_session_upload(client, src, dest) if msf_loaded?
}
elsif (stat.file?)
if client.fs.file.exists?(dest) and client.fs.file.stat(dest).directory?
client.fs.file.upload(dest, src) { |step, src, dst|
print_status("#{step.ljust(11)}: #{src} -> #{dst}")
client.framework.events.on_session_upload(client, src, dest) if msf_loaded?
}
else
client.fs.file.upload_file(dest, src) { |step, src, dst|
print_status("#{step.ljust(11)}: #{src} -> #{dst}")
client.framework.events.on_session_upload(client, src, dest) if msf_loaded?
}
end
end
}
return true
end
def cmd_upload_tabs(str, words)
return [] if words.length > 1
tab_complete_filenames(str, words)
end
end
end
end
end
end
| 25.237795 | 125 | 0.563771 |
ab8f7038d531a61c271e921f55ca7a16c6a98b3d | 8,015 | require 'puppet/util/autoload'
require 'puppet/parser/scope'
# A module for managing parser functions. Each specified function
# is added to a central module that then gets included into the Scope
# class.
#
# @api public
module Puppet::Parser::Functions
Environment = Puppet::Node::Environment
class << self
include Puppet::Util
end
# Reset the list of loaded functions.
#
# @api private
def self.reset
@functions = Hash.new { |h,k| h[k] = {} }
@modules = Hash.new
# Runs a newfunction to create a function for each of the log levels
Puppet::Util::Log.levels.each do |level|
newfunction(level, :doc => "Log a message on the server at level #{level.to_s}.") do |vals|
send(level, vals.join(" "))
end
end
end
# Accessor for singleton autoloader
#
# @api private
def self.autoloader
@autoloader ||= Puppet::Util::Autoload.new(
self, "puppet/parser/functions", :wrap => false
)
end
# Get the module that functions are mixed into corresponding to an
# environment
#
# @api private
def self.environment_module(env = nil)
if env and ! env.is_a?(Puppet::Node::Environment)
env = Puppet::Node::Environment.new(env)
end
@modules[ (env || Environment.current || Environment.root).name ] ||= Module.new
end
# Create a new Puppet DSL function.
#
# **The {newfunction} method provides a public API.**
#
# This method is used both internally inside of Puppet to define parser
# functions. For example, template() is defined in
# {file:lib/puppet/parser/functions/template.rb template.rb} using the
# {newfunction} method. Third party Puppet modules such as
# [stdlib](https://forge.puppetlabs.com/puppetlabs/stdlib) use this method to
# extend the behavior and functionality of Puppet.
#
# See also [Docs: Custom
# Functions](http://docs.puppetlabs.com/guides/custom_functions.html)
#
# @example Define a new Puppet DSL Function
# >> Puppet::Parser::Functions.newfunction(:double, :arity => 1,
# :doc => "Doubles an object, typically a number or string.",
# :type => :rvalue) {|i| i[0]*2 }
# => {:arity=>1, :type=>:rvalue,
# :name=>"function_double",
# :doc=>"Doubles an object, typically a number or string."}
#
# @example Invoke the double function from irb as is done in RSpec examples:
# >> require 'puppet_spec/scope'
# >> scope = PuppetSpec::Scope.create_test_scope_for_node('example')
# => Scope()
# >> scope.function_double([2])
# => 4
# >> scope.function_double([4])
# => 8
# >> scope.function_double([])
# ArgumentError: double(): Wrong number of arguments given (0 for 1)
# >> scope.function_double([4,8])
# ArgumentError: double(): Wrong number of arguments given (2 for 1)
# >> scope.function_double(["hello"])
# => "hellohello"
#
# @param [Symbol] name the name of the function represented as a ruby Symbol.
# The {newfunction} method will define a Ruby method based on this name on
# the parser scope instance.
#
# @param [Proc] block the block provided to the {newfunction} method will be
# executed when the Puppet DSL function is evaluated during catalog
# compilation. The arguments to the function will be passed as an array to
# the first argument of the block. The return value of the block will be
# the return value of the Puppet DSL function for `:rvalue` functions.
#
# @option options [:rvalue, :statement] :type (:statement) the type of function.
# Either `:rvalue` for functions that return a value, or `:statement` for
# functions that do not return a value.
#
# @option options [String] :doc ('') the documentation for the function.
# This string will be extracted by documentation generation tools.
#
# @option options [Integer] :arity (-1) the
# [arity](http://en.wikipedia.org/wiki/Arity) of the function. When
# specified as a positive integer the function is expected to receive
# _exactly_ the specified number of arguments. When specified as a
# negative number, the function is expected to receive _at least_ the
# absolute value of the specified number of arguments incremented by one.
# For example, a function with an arity of `-4` is expected to receive at
# minimum 3 arguments. A function with the default arity of `-1` accepts
# zero or more arguments. A function with an arity of 2 must be provided
# with exactly two arguments, no more and no less. Added in Puppet 3.1.0.
#
# @return [Hash] describing the function.
#
# @api public
def self.newfunction(name, options = {}, &block)
name = name.intern
Puppet.warning "Overwriting previous definition for function #{name}" if get_function(name)
arity = options[:arity] || -1
ftype = options[:type] || :statement
unless ftype == :statement or ftype == :rvalue
raise Puppet::DevError, "Invalid statement type #{ftype.inspect}"
end
# the block must be installed as a method because it may use "return",
# which is not allowed from procs.
real_fname = "real_function_#{name}"
environment_module.send(:define_method, real_fname, &block)
fname = "function_#{name}"
environment_module.send(:define_method, fname) do |*args|
Puppet::Util::Profiler.profile("Called #{name}") do
if args[0].is_a? Array
if arity >= 0 and args[0].size != arity
raise ArgumentError, "#{name}(): Wrong number of arguments given (#{args[0].size} for #{arity})"
elsif arity < 0 and args[0].size < (arity+1).abs
raise ArgumentError, "#{name}(): Wrong number of arguments given (#{args[0].size} for minimum #{(arity+1).abs})"
end
self.send(real_fname, args[0])
else
raise ArgumentError, "custom functions must be called with a single array that contains the arguments. For example, function_example([1]) instead of function_example(1)"
end
end
end
func = {:arity => arity, :type => ftype, :name => fname}
func[:doc] = options[:doc] if options[:doc]
add_function(name, func)
func
end
# Determine if a function is defined
#
# @param [Symbol] name the function
#
# @return [Symbol, false] The name of the function if it's defined,
# otherwise false.
#
# @api public
def self.function(name)
name = name.intern
func = nil
unless func = get_function(name)
autoloader.load(name, Environment.current)
func = get_function(name)
end
if func
func[:name]
else
false
end
end
def self.functiondocs
autoloader.loadall
ret = ""
merged_functions.sort { |a,b| a[0].to_s <=> b[0].to_s }.each do |name, hash|
ret << "#{name}\n#{"-" * name.to_s.length}\n"
if hash[:doc]
ret << Puppet::Util::Docs.scrub(hash[:doc])
else
ret << "Undocumented.\n"
end
ret << "\n\n- *Type*: #{hash[:type]}\n\n"
end
ret
end
# Determine whether a given function returns a value.
#
# @param [Symbol] name the function
#
# @api public
def self.rvalue?(name)
func = get_function(name)
func ? func[:type] == :rvalue : false
end
# Return the number of arguments a function expects.
#
# @param [Symbol] name the function
# @return [Integer] The arity of the function. See {newfunction} for
# the meaning of negative values.
#
# @api public
def self.arity(name)
func = get_function(name)
func ? func[:arity] : -1
end
class << self
private
def merged_functions
@functions[Environment.root].merge(@functions[Environment.current])
end
def get_function(name)
name = name.intern
merged_functions[name]
end
def add_function(name, func)
name = name.intern
@functions[Environment.current][name] = func
end
end
reset # initialize the class instance variables
end
| 32.848361 | 179 | 0.650655 |
6157cf186f2c5706e78659f2b43d2f56ebe3f04e | 421 | require 'spec_helper'
describe Opal::Server do
it 'serves source maps only if they are enbled on the Processor' do
original_value = Opal::Processor.source_map_enabled
begin
[true, false].each do |bool|
Opal::Processor.source_map_enabled = bool
expect(subject.source_map_enabled).to eq(bool)
end
ensure
Opal::Processor.source_map_enabled = original_value
end
end
end
| 26.3125 | 69 | 0.705463 |
1a6ee9463cc86a253fc8f464fd14bbf9a97baa79 | 129 | require 'test_helper'
class SpellsComponentTest < ActiveSupport::TestCase
# test "the truth" do
# assert true
# end
end
| 16.125 | 51 | 0.72093 |
08b1694c605c9f1fda2d3ea17bb3c40819f2ecb1 | 1,797 | # 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::EventHub::Mgmt::V2018_01_01_preview
module Models
#
# Properties to configure keyVault Properties
#
class KeyVaultProperties
include MsRestAzure
# @return [String] Name of the Key from KeyVault
attr_accessor :key_name
# @return [String] Uri of KeyVault
attr_accessor :key_vault_uri
# @return [String] Key Version
attr_accessor :key_version
#
# Mapper for KeyVaultProperties class as Ruby Hash.
# This will be used for serialization/deserialization.
#
def self.mapper()
{
client_side_validation: true,
required: false,
serialized_name: 'KeyVaultProperties',
type: {
name: 'Composite',
class_name: 'KeyVaultProperties',
model_properties: {
key_name: {
client_side_validation: true,
required: false,
serialized_name: 'keyName',
type: {
name: 'String'
}
},
key_vault_uri: {
client_side_validation: true,
required: false,
serialized_name: 'keyVaultUri',
type: {
name: 'String'
}
},
key_version: {
client_side_validation: true,
required: false,
serialized_name: 'keyVersion',
type: {
name: 'String'
}
}
}
}
}
end
end
end
end
| 26.043478 | 70 | 0.513077 |
910b2524518da2a5cd95ac14e08bdb790215d498 | 2,714 | # frozen_string_literal: true
module Fourier
module Commands
class Lint < Base
desc "tuist", "Lint the Swift code of the Tuist CLI"
option :fix, desc: "When passed, it fixes the issues", type: :boolean, default: false
def tuist
Services::Lint::Tuist.call(fix: options[:fix])
Services::Format::Swift.call(fix: options[:fix])
end
desc "tuistbench", "Lint the Swift code of the tuistbench project"
option :fix, desc: "When passed, it fixes the issues", type: :boolean, default: false
def tuistbench
Services::Lint::Tuistbench.call(fix: options[:fix])
end
desc "backbone", "Lint the Ruby code of the Backbone project"
option :fix, desc: "When passed, it fixes the issues", type: :boolean, default: false
def backbone
Services::Lint::Backbone.call(fix: options[:fix])
end
desc "cloud", "Lint the Ruby code of the Cloud project"
option :fix, desc: "When passed, it fixes the issues", type: :boolean, default: false
def cloud
Services::Lint::Cloud.call(fix: options[:fix])
end
desc "cocoapods-interactor", "Lint the Ruby code of the CocoaPods interactor project"
option :fix, desc: "When passed, it fixes the issues", type: :boolean, default: false
def cocoapods_interactor
Services::Lint::CocoapodsInteractor.call(fix: options[:fix])
end
desc "fixturegen", "Lint the Swift code of the fixturegen project"
option :fix, desc: "When passed, it fixes the issues", type: :boolean, default: false
def fixturegen
Services::Lint::Fixturegen.call(fix: options[:fix])
end
desc "fourier", "Lint the Ruby code of the fixturegen project"
option :fix, desc: "When passed, it fixes the issues", type: :boolean, default: false
def fourier
Services::Lint::Fourier.call(fix: options[:fix])
end
desc "lockfiles", "Ensures SPM and Tuist's generated lockfiles are consistent"
def lockfiles
Services::Lint::Lockfiles.call
end
desc "all", "Lint all the code in the repository"
option :fix, desc: "When passed, it fixes the issues", type: :boolean, default: false
def all
Services::Lint::Lockfiles.call
Services::Lint::Tuist.call(fix: options[:fix])
Services::Lint::Tuistbench.call(fix: options[:fix])
Services::Lint::Fixturegen.call(fix: options[:fix])
Services::Lint::CocoapodsInteractor.call(fix: options[:fix])
Services::Lint::Fourier.call(fix: options[:fix])
Services::Lint::Cloud.call(fix: options[:fix])
Services::Lint::Backbone.call(fix: options[:fix])
end
end
end
end
| 39.333333 | 91 | 0.651069 |
1a194331e12bdae53b0534bf53d2b05045b0e935 | 21,335 | require 'spree/core/validators/email'
require 'spree/order/checkout'
module Spree
class Order < Spree::Base
PAYMENT_STATES = %w(balance_due credit_owed failed paid void)
SHIPMENT_STATES = %w(backorder canceled partial pending ready shipped)
extend FriendlyId
friendly_id :number, slug_column: :number, use: :slugged
include Spree::Order::Checkout
include Spree::Order::CurrencyUpdater
include Spree::Order::Payments
include Spree::Order::StoreCredit
include Spree::Core::NumberGenerator.new(prefix: 'R')
include Spree::Core::TokenGenerator
extend Spree::DisplayMoney
money_methods :outstanding_balance, :item_total, :adjustment_total,
:included_tax_total, :additional_tax_total, :tax_total,
:shipment_total, :promo_total, :total
alias :display_ship_total :display_shipment_total
alias_attribute :ship_total, :shipment_total
MONEY_THRESHOLD = 100_000_000
MONEY_VALIDATION = {
presence: true,
numericality: {
greater_than: -MONEY_THRESHOLD,
less_than: MONEY_THRESHOLD,
allow_blank: true
},
format: { with: /\A-?\d+(?:\.\d{1,2})?\z/, allow_blank: true }
}.freeze
POSITIVE_MONEY_VALIDATION = MONEY_VALIDATION.deep_dup.tap do |validation|
validation.fetch(:numericality)[:greater_than_or_equal_to] = 0
end.freeze
NEGATIVE_MONEY_VALIDATION = MONEY_VALIDATION.deep_dup.tap do |validation|
validation.fetch(:numericality)[:less_than_or_equal_to] = 0
end.freeze
checkout_flow do
go_to_state :address
go_to_state :delivery
go_to_state :payment, if: ->(order) { order.payment_required? }
go_to_state :confirm, if: ->(order) { order.confirmation_required? }
go_to_state :complete
remove_transition from: :delivery, to: :confirm
end
self.whitelisted_ransackable_associations = %w[shipments user promotions bill_address ship_address line_items]
self.whitelisted_ransackable_attributes = %w[completed_at created_at email number state payment_state shipment_state total considered_risky]
attr_reader :coupon_code
attr_accessor :temporary_address, :temporary_credit_card
if Spree.user_class
belongs_to :user, class_name: Spree.user_class.to_s
belongs_to :created_by, class_name: Spree.user_class.to_s
belongs_to :approver, class_name: Spree.user_class.to_s
belongs_to :canceler, class_name: Spree.user_class.to_s
else
belongs_to :user
belongs_to :created_by
belongs_to :approver
belongs_to :canceler
end
belongs_to :bill_address, foreign_key: :bill_address_id, class_name: 'Spree::Address'
alias_attribute :billing_address, :bill_address
belongs_to :ship_address, foreign_key: :ship_address_id, class_name: 'Spree::Address'
alias_attribute :shipping_address, :ship_address
belongs_to :store, class_name: 'Spree::Store'
with_options dependent: :destroy do
has_many :state_changes, as: :stateful
has_many :line_items, -> { order(:created_at) }, inverse_of: :order
has_many :payments
has_many :return_authorizations, inverse_of: :order
has_many :adjustments, -> { order(:created_at) }, as: :adjustable
end
has_many :reimbursements, inverse_of: :order
has_many :line_item_adjustments, through: :line_items, source: :adjustments
has_many :shipment_adjustments, through: :shipments, source: :adjustments
has_many :inventory_units, inverse_of: :order
has_many :products, through: :variants
has_many :variants, through: :line_items
has_many :refunds, through: :payments
has_many :all_adjustments,
class_name: 'Spree::Adjustment',
foreign_key: :order_id,
dependent: :destroy,
inverse_of: :order
has_many :order_promotions, class_name: 'Spree::OrderPromotion'
has_many :promotions, through: :order_promotions, class_name: 'Spree::Promotion'
has_many :shipments, dependent: :destroy, inverse_of: :order do
def states
pluck(:state).uniq
end
end
accepts_nested_attributes_for :line_items
accepts_nested_attributes_for :bill_address
accepts_nested_attributes_for :ship_address
accepts_nested_attributes_for :payments
accepts_nested_attributes_for :shipments
# Needs to happen before save_permalink is called
before_validation :set_currency
before_validation :clone_billing_address, if: :use_billing?
attr_accessor :use_billing
before_create :create_token
before_create :link_by_email
before_update :homogenize_line_item_currencies, if: :currency_changed?
with_options presence: true do
validates :number, length: { maximum: 32, allow_blank: true }, uniqueness: { allow_blank: true }
validates :email, length: { maximum: 254, allow_blank: true }, email: { allow_blank: true }, if: :require_email
validates :item_count, numericality: { greater_than_or_equal_to: 0, less_than: 2**31, only_integer: true, allow_blank: true }
end
validates :payment_state, inclusion: { in: PAYMENT_STATES, allow_blank: true }
validates :shipment_state, inclusion: { in: SHIPMENT_STATES, allow_blank: true }
validates :item_total, POSITIVE_MONEY_VALIDATION
validates :adjustment_total, MONEY_VALIDATION
validates :included_tax_total, POSITIVE_MONEY_VALIDATION
validates :additional_tax_total, POSITIVE_MONEY_VALIDATION
validates :payment_total, MONEY_VALIDATION
validates :shipment_total, MONEY_VALIDATION
validates :promo_total, NEGATIVE_MONEY_VALIDATION
validates :total, MONEY_VALIDATION
delegate :update_totals, :persist_totals, to: :updater
delegate :merge!, to: :merger
delegate :firstname, :lastname, to: :bill_address, prefix: true, allow_nil: true
class_attribute :update_hooks
self.update_hooks = Set.new
class_attribute :line_item_comparison_hooks
self.line_item_comparison_hooks = Set.new
scope :created_between, ->(start_date, end_date) { where(created_at: start_date..end_date) }
scope :completed_between, ->(start_date, end_date) { where(completed_at: start_date..end_date) }
scope :complete, -> { where.not(completed_at: nil) }
scope :incomplete, -> { where(completed_at: nil) }
# shows completed orders first, by their completed_at date, then uncompleted orders by their created_at
scope :reverse_chronological, -> { order('spree_orders.completed_at IS NULL', completed_at: :desc, created_at: :desc) }
# Use this method in other gems that wish to register their own custom logic
# that should be called after Order#update
def self.register_update_hook(hook)
self.update_hooks.add(hook)
end
# Use this method in other gems that wish to register their own custom logic
# that should be called when determining if two line items are equal.
def self.register_line_item_comparison_hook(hook)
self.line_item_comparison_hooks.add(hook)
end
# For compatiblity with Calculator::PriceSack
def amount
line_items.inject(0.0) { |sum, li| sum + li.amount }
end
# Sum of all line item amounts pre-tax
def pre_tax_item_amount
line_items.to_a.sum(&:pre_tax_amount)
end
def currency
self[:currency] || Spree::Config[:currency]
end
def shipping_discount
shipment_adjustments.eligible.sum(:amount) * - 1
end
def completed?
completed_at.present?
end
# Indicates whether or not the user is allowed to proceed to checkout.
# Currently this is implemented as a check for whether or not there is at
# least one LineItem in the Order. Feel free to override this logic in your
# own application if you require additional steps before allowing a checkout.
def checkout_allowed?
line_items.count > 0
end
# Is this a free order in which case the payment step should be skipped
def payment_required?
total.to_f > 0.0
end
# If true, causes the confirmation step to happen during the checkout process
def confirmation_required?
Spree::Config[:always_include_confirm_step] ||
payments.valid.map(&:payment_method).compact.any?(&:payment_profiles_supported?) ||
# Little hacky fix for #4117
# If this wasn't here, order would transition to address state on confirm failure
# because there would be no valid payments any more.
confirm?
end
def backordered?
shipments.any?(&:backordered?)
end
# Returns the relevant zone (if any) to be used for taxation purposes.
# Uses default tax zone unless there is a specific match
def tax_zone
@tax_zone ||= Zone.match(tax_address) || Zone.default_tax
end
# Returns the address for taxation based on configuration
def tax_address
Spree::Config[:tax_using_ship_address] ? ship_address : bill_address
end
def updater
@updater ||= OrderUpdater.new(self)
end
def update_with_updater!
updater.update
end
def update!
warn "`update!` is deprecated as it conflicts with update! method of rails. Use `update_with_updater!` instead."
update_with_updater!
end
def merger
@merger ||= Spree::OrderMerger.new(self)
end
def clone_billing_address
if bill_address and self.ship_address.nil?
self.ship_address = bill_address.clone
else
self.ship_address.attributes = bill_address.attributes.except('id', 'updated_at', 'created_at')
end
true
end
def allow_cancel?
return false if !completed? || canceled?
shipment_state.nil? || %w{ready backorder pending}.include?(shipment_state)
end
def all_inventory_units_returned?
inventory_units.all? { |inventory_unit| inventory_unit.returned? }
end
def contents
@contents ||= Spree::OrderContents.new(self)
end
# Associates the specified user with the order.
def associate_user!(user, override_email = true)
self.user = user
self.email = user.email if override_email
self.created_by ||= user
self.bill_address ||= user.bill_address
self.ship_address ||= user.ship_address
changes = slice(:user_id, :email, :created_by_id, :bill_address_id, :ship_address_id)
# immediately persist the changes we just made, but don't use save
# since we might have an invalid address associated
self.class.unscoped.where(id: self).update_all(changes)
end
def quantity_of(variant, options = {})
line_item = find_line_item_by_variant(variant, options)
line_item ? line_item.quantity : 0
end
def find_line_item_by_variant(variant, options = {})
line_items.detect { |line_item|
line_item.variant_id == variant.id &&
line_item_options_match(line_item, options)
}
end
# This method enables extensions to participate in the
# "Are these line items equal" decision.
#
# When adding to cart, an extension would send something like:
# params[:product_customizations]={...}
#
# and would provide:
#
# def product_customizations_match
def line_item_options_match(line_item, options)
return true unless options
self.line_item_comparison_hooks.all? { |hook|
self.send(hook, line_item, options)
}
end
# Creates new tax charges if there are any applicable rates. If prices already
# include taxes then price adjustments are created instead.
def create_tax_charge!
Spree::TaxRate.adjust(self, line_items)
Spree::TaxRate.adjust(self, shipments) if shipments.any?
end
def update_line_item_prices!
transaction do
line_items.each(&:update_price)
save!
end
end
def outstanding_balance
if canceled?
-1 * payment_total
elsif reimbursements.includes(:refunds).size > 0
reimbursed = reimbursements.includes(:refunds).inject(0) do |sum, reimbursement|
sum + reimbursement.refunds.sum(:amount)
end
# If reimbursement has happened add it back to total to prevent balance_due payment state
# See: https://github.com/spree/spree/issues/6229
total - (payment_total + reimbursed)
else
total - payment_total
end
end
def outstanding_balance?
self.outstanding_balance != 0
end
def name
if (address = bill_address || ship_address)
address.full_name
end
end
def can_ship?
self.complete? || self.resumed? || self.awaiting_return? || self.returned?
end
def credit_cards
credit_card_ids = payments.from_credit_card.pluck(:source_id).uniq
CreditCard.where(id: credit_card_ids)
end
def valid_credit_cards
credit_card_ids = payments.from_credit_card.valid.pluck(:source_id).uniq
CreditCard.where(id: credit_card_ids)
end
# Finalizes an in progress order after checkout is complete.
# Called after transition to complete state when payments will have been processed
def finalize!
# lock all adjustments (coupon promotions, etc.)
all_adjustments.each{|a| a.close}
# update payment and shipment(s) states, and save
updater.update_payment_state
shipments.each do |shipment|
shipment.update!(self)
shipment.finalize!
end
updater.update_shipment_state
save!
updater.run_hooks
touch :completed_at
deliver_order_confirmation_email unless confirmation_delivered?
consider_risk
end
def fulfill!
shipments.each { |shipment| shipment.update!(self) if shipment.persisted? }
updater.update_shipment_state
save!
end
def deliver_order_confirmation_email
OrderMailer.confirm_email(id).deliver_later
update_column(:confirmation_delivered, true)
end
# Helper methods for checkout steps
def paid?
payment_state == 'paid' || payment_state == 'credit_owed'
end
def available_payment_methods
@available_payment_methods ||= PaymentMethod.available_on_front_end
end
def insufficient_stock_lines
line_items.select(&:insufficient_stock?)
end
##
# Check to see if any line item variants are discontinued.
# If so add error and restart checkout.
def ensure_line_item_variants_are_not_discontinued
if line_items.any?{ |li| !li.variant || li.variant.discontinued? }
restart_checkout_flow
errors.add(:base, Spree.t(:discontinued_variants_present))
false
else
true
end
end
def ensure_line_items_are_in_stock
if insufficient_stock_lines.present?
restart_checkout_flow
errors.add(:base, Spree.t(:insufficient_stock_lines_present))
false
else
true
end
end
def empty!
if completed?
raise Spree.t(:cannot_empty_completed_order)
else
line_items.destroy_all
updater.update_item_count
adjustments.destroy_all
shipments.destroy_all
state_changes.destroy_all
order_promotions.destroy_all
update_totals
persist_totals
restart_checkout_flow
self
end
end
def has_step?(step)
checkout_steps.include?(step)
end
def state_changed(name)
state = "#{name}_state"
if persisted?
old_state = self.send("#{state}_was")
new_state = self.send(state)
unless old_state == new_state
self.state_changes.create(
previous_state: old_state,
next_state: new_state,
name: name,
user_id: self.user_id
)
end
end
end
def coupon_code=(code)
@coupon_code = code.strip.downcase rescue nil
end
def can_add_coupon?
Spree::Promotion.order_activatable?(self)
end
def shipped?
%w(partial shipped).include?(shipment_state)
end
def create_proposed_shipments
all_adjustments.shipping.delete_all
shipments.destroy_all
self.shipments = Spree::Stock::Coordinator.new(self).shipments
end
def apply_free_shipping_promotions
Spree::PromotionHandler::FreeShipping.new(self).activate
shipments.each { |shipment| Adjustable::AdjustmentsUpdater.update(shipment) }
updater.update_shipment_total
persist_totals
end
# Clean shipments and make order back to address state
#
# At some point the might need to force the order to transition from address
# to delivery again so that proper updated shipments are created.
# e.g. customer goes back from payment step and changes order items
def ensure_updated_shipments
if shipments.any? && !self.completed?
self.shipments.destroy_all
self.update_column(:shipment_total, 0)
restart_checkout_flow
end
end
def restart_checkout_flow
self.update_columns(
state: 'cart',
updated_at: Time.current,
)
self.next! if self.line_items.size > 0
end
def refresh_shipment_rates(shipping_method_filter = ShippingMethod::DISPLAY_ON_FRONT_END)
shipments.map { |s| s.refresh_rates(shipping_method_filter) }
end
def shipping_eq_billing_address?
(bill_address.empty? && ship_address.empty?) || bill_address.same_as?(ship_address)
end
def set_shipments_cost
shipments.each(&:update_amounts)
updater.update_shipment_total
persist_totals
end
def is_risky?
payments.risky.size > 0
end
def canceled_by(user)
self.transaction do
cancel!
self.update_columns(
canceler_id: user.id,
canceled_at: Time.current,
)
end
end
def approved_by(user)
self.transaction do
approve!
self.update_columns(
approver_id: user.id,
approved_at: Time.current,
)
end
end
def approved?
!!self.approved_at
end
def can_approve?
!approved?
end
def consider_risk
if is_risky? && !approved?
considered_risky!
end
end
def considered_risky!
update_column(:considered_risky, true)
end
def approve!
update_column(:considered_risky, false)
end
def reload(options=nil)
remove_instance_variable(:@tax_zone) if defined?(@tax_zone)
super
end
def tax_total
included_tax_total + additional_tax_total
end
def quantity
line_items.sum(:quantity)
end
def has_non_reimbursement_related_refunds?
refunds.non_reimbursement.exists? ||
payments.offset_payment.exists? # how old versions of spree stored refunds
end
# determines whether the inventory is fully discounted
#
# Returns
# - true if inventory amount is the exact negative of inventory related adjustments
# - false otherwise
def fully_discounted?
adjustment_total + line_items.map(&:final_amount).sum == 0.0
end
alias_method :fully_discounted, :fully_discounted?
private
def create_store_credit_payment(payment_method, credit, amount)
payments.create!(
source: credit,
payment_method: payment_method,
amount: amount,
state: 'checkout',
response_code: credit.generate_authorization_code
)
end
def store_credit_amount(credit, total)
[credit.amount_remaining, total].min
end
def link_by_email
self.email = user.email if self.user
end
# Determine if email is required (we don't want validation errors before we hit the checkout)
def require_email
true unless new_record? or ['cart', 'address'].include?(state)
end
def ensure_line_items_present
unless line_items.present?
errors.add(:base, Spree.t(:there_are_no_items_for_this_order)) and return false
end
end
def ensure_available_shipping_rates
if shipments.empty? || shipments.any? { |shipment| shipment.shipping_rates.blank? }
# After this point, order redirects back to 'address' state and asks user to pick a proper address
# Therefore, shipments are not necessary at this point.
shipments.destroy_all
errors.add(:base, Spree.t(:items_cannot_be_shipped)) and return false
end
end
def after_cancel
shipments.each { |shipment| shipment.cancel! }
payments.completed.each { |payment| payment.cancel! }
# Free up authorized store credits
payments.store_credits.pending.each(&:void!)
send_cancel_email
self.update_with_updater!
end
def send_cancel_email
OrderMailer.cancel_email(id).deliver_later
end
def after_resume
shipments.each { |shipment| shipment.resume! }
consider_risk
end
def use_billing?
use_billing.in?([true, 'true', '1'])
end
def set_currency
self.currency = Spree::Config[:currency] if self[:currency].nil?
end
def create_token
self.guest_token ||= generate_guest_token
end
end
end
| 31.19152 | 145 | 0.685259 |
282042b2f09677db785abed79d663d7b61bf79c1 | 153 | module Applicants
class EmployedForm < BaseForm
form_for Applicant
attr_accessor :employed
validates :employed, presence: true
end
end
| 15.3 | 39 | 0.745098 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.