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
|
---|---|---|---|---|---|
6a4bd508f05c09bb7cdd83e9defa4dee39b7ce50 | 8,040 | #!/usr/bin/env ruby
require 'active_support/inflector'
module Flapjack
module Gateways
class JSONAPI < Sinatra::Base
module Helpers
module Resources
ISO8601_PAT = "(?:[1-9][0-9]*)?[0-9]{4}-" \
"(?:1[0-2]|0[1-9])-" \
"(?:3[0-1]|0[1-9]|[1-2][0-9])T" \
"(?:2[0-3]|[0-1][0-9]):" \
"[0-5][0-9]:[0-5][0-9](?:\\.[0-9]+)?" \
"(?:Z|[+-](?:2[0-3]|[0-1][0-9]):[0-5][0-9])?"
# TODO refactor some of these methods into a module, included in data/ classes
def normalise_json_data(attribute_types, data)
record_data = data.dup
attribute_types.each_pair do |name, type|
t = record_data[name.to_s]
next unless t.is_a?(String) && :timestamp.eql?(type)
begin
record_data[name.to_s] = DateTime.parse(t)
rescue ArgumentError
record_data[name.to_s] = nil
end
end
symbolize(record_data)
end
def parse_range_or_value(name, pattern, v, opts = {}, &block)
rangeable = opts[:rangeable]
if rangeable && (v =~ /\A(?:(#{pattern})\.\.(#{pattern})|(#{pattern})\.\.|\.\.(#{pattern}))\z/)
start = nil
start_s = Regexp.last_match(1) || Regexp.last_match(3)
unless start_s.nil?
start = yield(start_s)
halt(err(403, "Couldn't parse #{name} '#{start_s}'")) if start.nil?
end
finish = nil
finish_s = Regexp.last_match(2) || Regexp.last_match(4)
unless finish_s.nil?
finish = yield(finish_s)
halt(err(403, "Couldn't parse #{name} '#{finish_s}'")) if finish.nil?
end
if !start.nil? && !finish.nil? && (start > finish)
halt(err(403, "Range order cannot be inversed"))
else
Zermelo::Filters::IndexRange.new(start, finish, :by_score => true)
end
elsif v =~ /\A#{pattern}\z/
t = yield(v)
halt(err(403, "Couldn't parse #{name} '#{v}'")) if t.nil?
t
else
halt(err(403, "Invalid #{name} parameter '#{v}'"))
end
end
def filter_params(klass, filter)
attributes = if klass.respond_to?(:jsonapi_methods)
(klass.jsonapi_methods[:get] || {}).attributes || []
else
[]
end
attribute_types = klass.attribute_types
rangeable_attrs = []
attrs_by_type = {}
klass.send(:with_index_data) do |idx_data|
idx_data.each do |k, d|
next unless d.index_klass == ::Zermelo::Associations::RangeIndex
rangeable_attrs << k
end
end
Zermelo::ATTRIBUTE_TYPES.keys.each do |at|
attrs_by_type[at] = attributes.select do |a|
at.eql?(attribute_types[a])
end
end
filter.each_with_object({}) do |filter_str, memo|
k, v = filter_str.split(':', 2)
halt(err(403, "Single filter parameters must be 'key:value'")) if k.nil? || v.nil?
value = if attrs_by_type[:string].include?(k.to_sym) || :id.eql?(k.to_sym)
if v =~ %r{^/(.+)/$}
Regexp.new(Regexp.last_match(1))
elsif v =~ /\|/
v.split('|')
else
v
end
elsif attrs_by_type[:boolean].include?(k.to_sym)
case v.downcase
when '0', 'f', 'false', 'n', 'no'
false
when '1', 't', 'true', 'y', 'yes'
true
end
elsif attrs_by_type[:timestamp].include?(k.to_sym)
parse_range_or_value('timestamp', ISO8601_PAT, v, :rangeable => rangeable_attrs.include?(k.to_sym)) {|s|
begin; DateTime.parse(s); rescue ArgumentError; nil; end
}
elsif attrs_by_type[:integer].include?(k.to_sym)
parse_range_or_value('integer', '\d+', v, :rangeable => rangeable_attrs.include?(k.to_sym)) {|s|
s.to_i
}
elsif attrs_by_type[:float].include?(k.to_sym)
parse_range_or_value('float', '\d+(\.\d+)?', v, :rangeable => rangeable_attrs.include?(k.to_sym)) {|s|
s.to_f
}
end
halt(err(403, "Invalid filter key '#{k}'")) if value.nil?
memo[k.to_sym] = value
end
end
def resource_filter_sort(klass, options = {})
options[:sort] ||= 'id'
scope = klass
unless params[:filter].nil?
unless params[:filter].is_a?(Array)
halt(err(403, "Filter parameters must be passed as an Array"))
end
filter_ops = filter_params(klass, params[:filter])
scope = scope.intersect(filter_ops)
end
sort_opts = if params[:sort].nil?
options[:sort].to_sym
else
sort_params = params[:sort].split(',')
if sort_params.any? {|sp| sp !~ /^(?:\+|-)/ }
halt(err(403, "Sort parameters must start with +/-"))
end
sort_params.each_with_object({}) do |sort_param, memo|
sort_param =~ /^(\+|\-)([a-z_]+)$/i
rev = Regexp.last_match(1)
term = Regexp.last_match(2)
memo[term.to_sym] = (rev == '-') ? :desc : :asc
end
end
scope = scope.sort(sort_opts)
scope
end
def paginate_get(dataset, options = {})
return([[], {}, {}]) if dataset.nil?
total = dataset.count
return([[], {}, {}]) if total == 0
page = options[:page].to_i
page = (page > 0) ? page : 1
per_page = options[:per_page].to_i
per_page = (per_page > 0) ? per_page : 20
total_pages = (total.to_f / per_page).ceil
pages = set_page_numbers(page, total_pages)
links = create_links(pages)
headers['Link'] = create_link_header(links) unless links.empty?
headers['Total-Count'] = total_pages.to_s
[dataset.page(page, :per_page => per_page),
links,
{
:pagination => {
:page => page,
:per_page => per_page,
:total_pages => total_pages,
:total_count => total
}
}
]
end
def set_page_numbers(page, total_pages)
pages = {}
pages[:first] = 1 # if (total_pages > 1) && (page > 1)
pages[:prev] = page - 1 if (page > 1)
pages[:next] = page + 1 if page < total_pages
pages[:last] = total_pages # if (total_pages > 1) && (page < total_pages)
pages
end
def create_links(pages)
url_without_params = request.url.split('?').first
per_page = params[:per_page] # ? params[:per_page].to_i : 20
links = {}
pages.each do |key, value|
page_params = {'page' => value }
page_params.update('per_page' => per_page) unless per_page.nil?
new_params = request.params.merge(page_params)
links[key] = "#{url_without_params}?#{new_params.to_query}"
end
links
end
def create_link_header(links)
links.collect {|(k, v)| "<#{v}; rel=\"#{k}\"" }.join(', ')
end
end
end
end
end
end | 35.418502 | 120 | 0.465174 |
bbaa0784ef24f71d4e61182f4a013a3f9f29c316 | 331 | require 'spec_helper'
describe "One-liner should syntax" do
subject { 42 }
describe "should" do
it { should == 42 }
it { should_not == 43 }
end
describe "is_expected" do
it { is_expected.to eq(42) }
it { is_expected.to_not eq(43) }
end
describe "expect" do
it { expect(42).to eq(42) }
end
end
| 16.55 | 37 | 0.616314 |
0366259d677031431c61b80bf45fa2618731a078 | 485 | # frozen_string_literal: true
module Facts
module Freebsd
module Memory
module Swap
class Used
FACT_NAME = 'memory.swap.used'
def call_the_resolver
fact_value = Facter::Resolvers::Freebsd::SwapMemory.resolve(:used_bytes)
fact_value = Facter::FactsUtils::UnitConverter.bytes_to_human_readable(fact_value)
Facter::ResolvedFact.new(FACT_NAME, fact_value)
end
end
end
end
end
end
| 23.095238 | 94 | 0.643299 |
bb45380c4346222f39f5034e587dc3bb645494d9 | 1,165 | # Load libkv adapter and plugins and add libkv 'extension' to the catalog
# instance, if it is not present
#
# @author https://github.com/simp/pupmod-simp-libkv/graphs/contributors
#
Puppet::Functions.create_function(:'libkv::support::load') do
# @return [Nil]
# @raise LoadError if libkv adapter software fails to load
#
dispatch :load do
end
def load
catalog = closure_scope.find_global_scope.catalog
unless catalog.respond_to?(:libkv)
# load and instantiate libkv adapter and then add it as a
# 'libkv' attribute to the catalog instance
lib_dir = File.dirname(File.dirname(File.dirname(File.dirname(File.dirname("#{__FILE__}")))))
filename = File.join(lib_dir, 'puppet_x', 'libkv', 'loader.rb')
if File.exists?(filename)
begin
catalog.instance_eval(File.read(filename), filename)
rescue SyntaxError => e
raise(LoadError,
"libkv Internal Error: unable to load #{filename}: #{e.message}"
)
end
else
raise(LoadError,
"libkv Internal Error: unable to load #{filename}: File not found"
)
end
end
end
end
| 30.657895 | 99 | 0.654077 |
01588e428906d60558ffcb6c48d4b13ea7cb99ab | 1,148 | # Generated by the protocol buffer compiler. DO NOT EDIT!
# source: google/ads/googleads/v6/resources/payments_account.proto
require 'google/protobuf'
require 'google/api/field_behavior_pb'
require 'google/api/resource_pb'
require 'google/api/annotations_pb'
Google::Protobuf::DescriptorPool.generated_pool.build do
add_file("google/ads/googleads/v6/resources/payments_account.proto", :syntax => :proto3) do
add_message "google.ads.googleads.v6.resources.PaymentsAccount" do
optional :resource_name, :string, 1
proto3_optional :payments_account_id, :string, 8
proto3_optional :name, :string, 9
proto3_optional :currency_code, :string, 10
proto3_optional :payments_profile_id, :string, 11
proto3_optional :secondary_payments_profile_id, :string, 12
proto3_optional :paying_manager_customer, :string, 13
end
end
end
module Google
module Ads
module GoogleAds
module V6
module Resources
PaymentsAccount = ::Google::Protobuf::DescriptorPool.generated_pool.lookup("google.ads.googleads.v6.resources.PaymentsAccount").msgclass
end
end
end
end
end
| 33.764706 | 146 | 0.748258 |
2690d58fe2a37c8587368ee6976efadfcaedea76 | 139 | # Be sure to restart your server when you modify this file.
Rails.application.config.session_store :cookie_store, key: '_raceday_session'
| 34.75 | 77 | 0.805755 |
01e042e2e92ee453a2a0a5156635f7d7da6b205d | 1,284 | # quietube
# by chetan sarva <[email protected]> 2009-11-24
#
# posts shortened quietube version of youtube links with optional title
require '0lib_rbot'
require 'shorturl'
class QuietubePlugin < Plugin
include PluginLib
Config.register Config::BooleanValue.new("quietube.display_title",
:default => false,
:desc => "Fetch and display video title")
def initialize
super
self.filter_group = :htmlinfo
load_filters
end
def listen(m)
return unless m.kind_of?(PrivMessage)
urls = extract_urls(m)
urls.each { |url|
next if url !~ %r{http://www\.youtube\.com/watch\?v=}
title = nil
if @bot.config["quietube.display_title"] then
# get title
uri = url.kind_of?(URI) ? url : URI.parse(url)
info = @bot.filter(:htmlinfo, uri)
title = info[:title]
title = " -> #{title}" if not title.nil?
end
quieter = "http://quietube.com/v.php/#{url}"
link = ShortURL.shorten(quieter, :tinyurl)
m.reply "quieter: #{link}#{title}"
}
end
end
plugin = QuietubePlugin.new
plugin.register("quietube") | 24.692308 | 71 | 0.553738 |
26ecd8ceeace8395eb1db3835155fe969674eb1a | 2,992 | # This file is auto-generated from the current state of the database. Instead
# of editing this file, please use the migrations feature of Active Record to
# incrementally modify your database, and then regenerate this schema definition.
#
# Note that this schema.rb definition is the authoritative source for your
# database schema. If you need to create the application database on another
# system, you should be using db:schema:load, not running all the migrations
# from scratch. The latter is a flawed and unsustainable approach (the more migrations
# you'll amass, the slower it'll run and the greater likelihood for issues).
#
# It's strongly recommended that you check this file into your version control system.
ActiveRecord::Schema.define(version: 20171015181846) do
# These are extensions that must be enabled in order to support this database
enable_extension "plpgsql"
create_table "application_attachments", force: :cascade do |t|
t.integer "application_id"
t.integer "attachment_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
create_table "application_company_relationships", id: false, force: :cascade do |t|
t.integer "application_id"
t.integer "company_id"
end
create_table "application_notes", force: :cascade do |t|
t.integer "application_id"
t.integer "note_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
create_table "applications", force: :cascade do |t|
t.string "position"
t.string "company_name"
t.text "description"
t.string "location"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.integer "status_id", default: 1
t.string "document"
t.string "posting_url"
end
create_table "attachments", force: :cascade do |t|
t.string "name"
t.string "document"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
create_table "companies", force: :cascade do |t|
t.string "name"
t.string "industry"
t.text "website"
t.decimal "overall_rating"
t.string "square_logo"
t.string "ceo_name"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
create_table "emails", force: :cascade do |t|
t.string "subject"
t.text "body"
t.string "to"
t.string "from"
t.date "date"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.integer "application_id"
end
create_table "notes", force: :cascade do |t|
t.date "date"
t.text "content"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
create_table "statuses", force: :cascade do |t|
t.string "name"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
end
| 32.521739 | 86 | 0.677139 |
2102f1dbfb14c65c20355f0c86ecae56c16b2a55 | 2,354 | # frozen_string_literal: true
Rails.application.configure do
# Settings specified here will take precedence over those in config/application.rb.
# In the development environment your application's code is reloaded on
# every request. This slows down response time but is perfect for development
# since you don't have to restart the web server when you make code changes.
config.cache_classes = false
# Do not eager load code on boot.
config.eager_load = false
# Show full error reports.
config.consider_all_requests_local = true
# Enable/disable caching. By default caching is disabled.
# Run rails dev:cache to toggle caching.
if Rails.root.join('tmp', 'caching-dev.txt').exist?
config.action_controller.perform_caching = true
config.action_controller.enable_fragment_cache_logging = true
config.cache_store = :memory_store
config.public_file_server.headers = {
'Cache-Control' => "public, max-age=#{2.days.to_i}"
}
else
config.action_controller.perform_caching = false
config.cache_store = :null_store
end
# Store uploaded files on the local file system (see config/storage.yml for options).
config.active_storage.service = :local
# Don't care if the mailer can't send.
config.action_mailer.raise_delivery_errors = false
config.action_mailer.perform_caching = false
# Print deprecation notices to the Rails logger.
config.active_support.deprecation = :log
# Raise an error on page load if there are pending migrations.
config.active_record.migration_error = :page_load
# Highlight code that triggered database queries in logs.
config.active_record.verbose_query_logs = true
# Debug mode disables concatenation and preprocessing of assets.
# This option may cause significant delays in view rendering with a large
# number of complex assets.
config.assets.debug = true
# Suppress logger output for asset requests.
config.assets.quiet = true
# Raises error for missing translations.
# config.action_view.raise_on_missing_translations = true
# Use an evented file watcher to asynchronously detect changes in source code,
# routes, locales, etc. This feature depends on the listen gem.
config.file_watcher = ActiveSupport::EventedFileUpdateChecker
config.action_mailer.default_url_options = { host: 'localhost', port: 3000 }
end
| 35.134328 | 87 | 0.763381 |
332d7639ee64a704dc4a51b6456a58ad6c3c116d | 2,051 | RSpec.describe Mutant::Reporter::CLI::Printer::EnvProgress do
setup_shared_context
let(:reportable) { env_result }
describe '.call' do
context 'without progress' do
with(:subject_a_result) { { mutation_results: [] } }
it_reports <<-'STR'
Mutant configuration:
Matcher: #<Mutant::Matcher::Config empty>
Integration: Mutant::Integration::Null
Jobs: 1
Includes: []
Requires: []
Subjects: 1
Mutations: 2
Results: 0
Kills: 0
Alive: 0
Runtime: 4.00s
Killtime: 0.00s
Overhead: Inf%
Mutations/s: 0.00
Coverage: 100.00%
STR
end
context 'on full coverage' do
it_reports <<-'STR'
Mutant configuration:
Matcher: #<Mutant::Matcher::Config empty>
Integration: Mutant::Integration::Null
Jobs: 1
Includes: []
Requires: []
Subjects: 1
Mutations: 2
Results: 2
Kills: 2
Alive: 0
Runtime: 4.00s
Killtime: 2.00s
Overhead: 100.00%
Mutations/s: 0.50
Coverage: 100.00%
STR
end
context 'on partial coverage' do
with(:mutation_a_test_result) { { passed: true } }
it_reports <<-'STR'
Mutant configuration:
Matcher: #<Mutant::Matcher::Config empty>
Integration: Mutant::Integration::Null
Jobs: 1
Includes: []
Requires: []
Subjects: 1
Mutations: 2
Results: 2
Kills: 1
Alive: 1
Runtime: 4.00s
Killtime: 2.00s
Overhead: 100.00%
Mutations/s: 0.50
Coverage: 50.00%
STR
end
end
end
| 27.346667 | 61 | 0.450512 |
212756637a4b5a4b17576b96f82e342876aa8fa6 | 180 | module ARuby
class Config
class ARubyConfig < Base
Config.configures :aruby, self
attr_accessor :log_output
attr_accessor :debug_enabled
end
end
end
| 16.363636 | 36 | 0.694444 |
5de6f8e868e75a8a4bacd1225e5a1a8354c0adfb | 861 | ENV['RAILS_ENV'] ||= 'test'
require_relative '../config/environment'
require 'rails/test_help'
class ActiveSupport::TestCase
# Run tests in parallel with specified workers
parallelize(workers: :number_of_processors)
# Setup all fixtures in test/fixtures/*.yml for all tests in alphabetical order.
fixtures :all
# テストユーザーがログイン中の場合にtrueを返す
def is_logged_in?
!session[:user_id].nil?
end
# Add more helper methods to be used by all tests here...
def log_in_as(user)
session[:user_id] = user.id
end
class ActionDispatch::IntegrationTest
# テストユーザーとしてログインする
def log_in_as(user, password: 'password', remember_me: '1')
post login_path, params: { session: { email: user.email,
password: password,
remember_me: remember_me } }
end
end
end | 26.090909 | 82 | 0.659698 |
031d246d997232f02d324494b18deaea523cf296 | 10,008 | # ==========================================
# CMock Project - Automatic Mock Generation for C
# Copyright (c) 2007 Mike Karlesky, Mark VanderVoord, Greg Williams
# [Released under MIT License. Please refer to license.txt for details]
# ==========================================
require File.expand_path(File.dirname(__FILE__)) + "/../test_helper"
require File.expand_path(File.dirname(__FILE__)) + '/../../lib/cmock_generator_plugin_expect'
describe CMockGeneratorPluginExpect, "Verify CMockGeneratorPluginExpect Module with Global Ordering" do
before do
create_mocks :config, :utils
@config = create_stub(
:when_ptr => :compare_data,
:enforce_strict_ordering => true,
:respond_to? => true,
:plugins => [ :expect, :expect_any_args ] )
@utils.expect :helpers, {}
@cmock_generator_plugin_expect = CMockGeneratorPluginExpect.new(@config, @utils)
end
after do
end
it "have set up internal priority on init" do
assert_nil(@cmock_generator_plugin_expect.unity_helper)
assert_equal(5, @cmock_generator_plugin_expect.priority)
end
it "not include any additional include files" do
assert(!@cmock_generator_plugin_expect.respond_to?(:include_files))
end
it "add to typedef structure mock needs of functions of style 'void func(void)' and global ordering" do
function = {:name => "Oak", :args => [], :return => test_return[:void]}
expected = " int CallOrder;\n"
returned = @cmock_generator_plugin_expect.instance_typedefs(function)
assert_equal(expected, returned)
end
it "add to typedef structure mock needs of functions of style 'int func(void)'" do
function = {:name => "Elm", :args => [], :return => test_return[:int]}
expected = " int ReturnVal;\n int CallOrder;\n"
returned = @cmock_generator_plugin_expect.instance_typedefs(function)
assert_equal(expected, returned)
end
it "add to typedef structure mock needs of functions of style 'void func(int chicken, char* pork)'" do
function = {:name => "Cedar", :args => [{ :name => "chicken", :type => "int"}, { :name => "pork", :type => "char*"}], :return => test_return[:void]}
expected = " int CallOrder;\n int Expected_chicken;\n char* Expected_pork;\n"
returned = @cmock_generator_plugin_expect.instance_typedefs(function)
assert_equal(expected, returned)
end
it "add to typedef structure mock needs of functions of style 'int func(float beef)'" do
function = {:name => "Birch", :args => [{ :name => "beef", :type => "float"}], :return => test_return[:int]}
expected = " int ReturnVal;\n int CallOrder;\n float Expected_beef;\n"
returned = @cmock_generator_plugin_expect.instance_typedefs(function)
assert_equal(expected, returned)
end
it "add mock function declaration for functions of style 'void func(void)'" do
function = {:name => "Maple", :args => [], :return => test_return[:void]}
expected = "#define Maple_Expect() Maple_CMockExpect(__LINE__)\n" +
"void Maple_CMockExpect(UNITY_LINE_TYPE cmock_line);\n"
returned = @cmock_generator_plugin_expect.mock_function_declarations(function)
assert_equal(expected, returned)
end
it "add mock function declaration for functions of style 'int func(void)'" do
function = {:name => "Spruce", :args => [], :return => test_return[:int]}
expected = "#define Spruce_ExpectAndReturn(cmock_retval) Spruce_CMockExpectAndReturn(__LINE__, cmock_retval)\n" +
"void Spruce_CMockExpectAndReturn(UNITY_LINE_TYPE cmock_line, int cmock_to_return);\n"
returned = @cmock_generator_plugin_expect.mock_function_declarations(function)
assert_equal(expected, returned)
end
it "add mock function declaration for functions of style 'const char* func(int tofu)'" do
function = {:name => "Pine", :args => ["int tofu"], :args_string => "int tofu", :args_call => 'tofu', :return => test_return[:string]}
expected = "#define Pine_ExpectAndReturn(tofu, cmock_retval) Pine_CMockExpectAndReturn(__LINE__, tofu, cmock_retval)\n" +
"void Pine_CMockExpectAndReturn(UNITY_LINE_TYPE cmock_line, int tofu, const char* cmock_to_return);\n"
returned = @cmock_generator_plugin_expect.mock_function_declarations(function)
assert_equal(expected, returned)
end
it "add mock function implementation for functions of style 'void func(void)'" do
function = {:name => "Apple", :args => [], :return => test_return[:void]}
expected = ""
returned = @cmock_generator_plugin_expect.mock_implementation(function)
assert_equal(expected, returned)
end
it "add mock function implementation for functions of style 'int func(int veal, unsigned int sushi)'" do
function = {:name => "Cherry", :args => [ { :type => "int", :name => "veal" }, { :type => "unsigned int", :name => "sushi" } ], :return => test_return[:int]}
@utils.expect :code_verify_an_arg_expectation, "mocked_retval_1\n", [function, function[:args][0]]
@utils.expect :code_verify_an_arg_expectation, "mocked_retval_2\n", [function, function[:args][1]]
expected = " if (cmock_call_instance->IgnoreMode != CMOCK_ARG_NONE)\n" +
" {\n" +
"mocked_retval_1\n" +
"mocked_retval_2\n" +
" }\n"
returned = @cmock_generator_plugin_expect.mock_implementation(function)
assert_equal(expected, returned)
end
it "add mock function implementation using ordering if needed" do
function = {:name => "Apple", :args => [], :return => test_return[:void]}
expected = ""
@cmock_generator_plugin_expect.ordered = true
returned = @cmock_generator_plugin_expect.mock_implementation(function)
assert_equal(expected, returned)
end
it "add mock function implementation for functions of style 'void func(int worm)' and strict ordering" do
function = {:name => "Apple", :args => [{ :type => "int", :name => "worm" }], :return => test_return[:void]}
@utils.expect :code_verify_an_arg_expectation, "mocked_retval_0\n", [function, function[:args][0]]
expected = " if (cmock_call_instance->IgnoreMode != CMOCK_ARG_NONE)\n" +
" {\n" +
"mocked_retval_0\n" +
" }\n"
@cmock_generator_plugin_expect.ordered = true
returned = @cmock_generator_plugin_expect.mock_implementation(function)
assert_equal(expected, returned)
end
it "add mock interfaces for functions of style 'void func(void)'" do
function = {:name => "Pear", :args => [], :args_string => "void", :return => test_return[:void]}
@utils.expect :code_add_base_expectation, "mock_retval_0\n", ["Pear"]
@utils.expect :code_call_argument_loader, "mock_retval_1\n", [function]
expected = ["void Pear_CMockExpect(UNITY_LINE_TYPE cmock_line)\n",
"{\n",
"mock_retval_0\n",
"mock_retval_1\n",
" UNITY_CLR_DETAILS();\n",
"}\n\n"
].join
returned = @cmock_generator_plugin_expect.mock_interfaces(function)
assert_equal(expected, returned)
end
it "add mock interfaces for functions of style 'int func(void)'" do
function = {:name => "Orange", :args => [], :args_string => "void", :return => test_return[:int]}
@utils.expect :code_add_base_expectation, "mock_retval_0\n", ["Orange"]
@utils.expect :code_call_argument_loader, "mock_retval_1\n", [function]
@utils.expect :code_assign_argument_quickly, "mock_retval_2\n", ["cmock_call_instance->ReturnVal", function[:return]]
expected = ["void Orange_CMockExpectAndReturn(UNITY_LINE_TYPE cmock_line, int cmock_to_return)\n",
"{\n",
"mock_retval_0\n",
"mock_retval_1\n",
"mock_retval_2\n",
" UNITY_CLR_DETAILS();\n",
"}\n\n"
].join
returned = @cmock_generator_plugin_expect.mock_interfaces(function)
assert_equal(expected, returned)
end
it "add mock interfaces for functions of style 'int func(char* pescado)'" do
function = {:name => "Lemon", :args => [{ :type => "char*", :name => "pescado"}], :args_string => "char* pescado", :return => test_return[:int]}
@utils.expect :code_add_base_expectation, "mock_retval_0\n", ["Lemon"]
@utils.expect :code_call_argument_loader, "mock_retval_1\n", [function]
@utils.expect :code_assign_argument_quickly, "mock_retval_2\n", ["cmock_call_instance->ReturnVal", function[:return]]
expected = ["void Lemon_CMockExpectAndReturn(UNITY_LINE_TYPE cmock_line, char* pescado, int cmock_to_return)\n",
"{\n",
"mock_retval_0\n",
"mock_retval_1\n",
"mock_retval_2\n",
" UNITY_CLR_DETAILS();\n",
"}\n\n"
].join
returned = @cmock_generator_plugin_expect.mock_interfaces(function)
assert_equal(expected, returned)
end
it "add mock interfaces for functions when using ordering" do
function = {:name => "Pear", :args => [], :args_string => "void", :return => test_return[:void]}
@utils.expect :code_add_base_expectation, "mock_retval_0\n", ["Pear"]
@utils.expect :code_call_argument_loader, "mock_retval_1\n", [function]
expected = ["void Pear_CMockExpect(UNITY_LINE_TYPE cmock_line)\n",
"{\n",
"mock_retval_0\n",
"mock_retval_1\n",
" UNITY_CLR_DETAILS();\n",
"}\n\n"
].join
@cmock_generator_plugin_expect.ordered = true
returned = @cmock_generator_plugin_expect.mock_interfaces(function)
assert_equal(expected, returned)
end
it "add mock verify lines" do
function = {:name => "Banana" }
expected = " UNITY_SET_DETAIL(CMockString_Banana);\n" +
" UNITY_TEST_ASSERT(CMOCK_GUTS_NONE == Mock.Banana_CallInstance, cmock_line, CMockStringCalledLess);\n"
returned = @cmock_generator_plugin_expect.mock_verify(function)
assert_equal(expected, returned)
end
end
| 49.058824 | 161 | 0.666167 |
ffab46bf270fbe66e60b868940aa9679ebef897f | 957 | cask "app-fair" do
version "0.8.53"
sha256 "e97179eaafe761341f6a80525cca20384defcf4fbbc58ae2c480a7d1972d2a51"
url "https://github.com/App-Fair/App/releases/download/#{version}/App-Fair-macOS.zip",
verified: "github.com/App-Fair/App/"
name "App Fair"
desc "Catalog of free and commercial native desktop applications"
homepage "https://appfair.app/"
depends_on macos: ">= :monterey"
app "App Fair.app"
binary "#{appdir}/App Fair.app/Contents/MacOS/App Fair", target: "app-fair"
zap trash: [
"~/Library/Application Scripts/app.App-Fair",
"~/Library/Application Support/app.App-Fair",
"~/Library/Caches/app.App-Fair",
"~/Library/Containers/app.App-Fair",
"~/Library/HTTPStorages/app.App-Fair",
"~/Library/HTTPStorages/app.App-Fair.binarycookies",
"~/Library/Preferences/app.App-Fair.plist",
"~/Library/Saved Application State/app.App-Fair.savedState",
],
rmdir: "/Applications/App Fair"
end
| 34.178571 | 88 | 0.703239 |
4a0cc8c536259c9373b27c3237ce344a922de01e | 170 | module IshBlog
class ApplicationController < ActionController::Base
def current_ability
@current_ability ||= IshBlog::Ability.new(current_user)
end
end
end
| 21.25 | 59 | 0.764706 |
38d7c804384fdf2f3d52cbb25360a533761504e3 | 1,824 | unless ENV["HOMEBREW_BREW_FILE"]
raise "HOMEBREW_BREW_FILE was not exported! Please call bin/brew directly!"
end
# Path to `bin/brew` main executable in HOMEBREW_PREFIX
HOMEBREW_BREW_FILE = Pathname.new(ENV["HOMEBREW_BREW_FILE"])
# Where we link under
HOMEBREW_PREFIX = Pathname.new(ENV["HOMEBREW_PREFIX"])
# Where .git is found
HOMEBREW_REPOSITORY = Pathname.new(ENV["HOMEBREW_REPOSITORY"])
# Where we store most of Homebrew, taps, and various metadata
HOMEBREW_LIBRARY = Pathname.new(ENV["HOMEBREW_LIBRARY"])
# Where shim scripts for various build and SCM tools are stored
HOMEBREW_SHIMS_PATH = HOMEBREW_LIBRARY/"Homebrew/shims"
# Where we store symlinks to currently linked kegs
HOMEBREW_LINKED_KEGS = HOMEBREW_PREFIX/"var/homebrew/linked"
# Where we store symlinks to currently version-pinned kegs
HOMEBREW_PINNED_KEGS = HOMEBREW_PREFIX/"var/homebrew/pinned"
# Where we store lock files
HOMEBREW_LOCK_DIR = HOMEBREW_PREFIX/"var/homebrew/locks"
# Where we store built products
HOMEBREW_CELLAR = Pathname.new(ENV["HOMEBREW_CELLAR"])
# Where downloads (bottles, source tarballs, etc.) are cached
HOMEBREW_CACHE = Pathname.new(ENV["HOMEBREW_CACHE"])
# Where brews installed via URL are cached
HOMEBREW_CACHE_FORMULA = HOMEBREW_CACHE/"Formula"
# Where build, postinstall, and test logs of formulae are written to
HOMEBREW_LOGS = Pathname.new(ENV["HOMEBREW_LOGS"] || "~/Library/Logs/Homebrew/").expand_path
# Must use /tmp instead of $TMPDIR because long paths break Unix domain sockets
HOMEBREW_TEMP = Pathname.new(ENV.fetch("HOMEBREW_TEMP", "/tmp"))
unless defined? HOMEBREW_LIBRARY_PATH
# Root of the Homebrew code base
HOMEBREW_LIBRARY_PATH = Pathname.new(__FILE__).realpath.parent
end
# Load path used by standalone scripts to access the Homebrew code base
HOMEBREW_LOAD_PATH = HOMEBREW_LIBRARY_PATH
| 35.764706 | 92 | 0.795504 |
b90f5eae9163da1e6af7debb8cef87211f747fc3 | 1,344 | =begin
#Selling Partner API for Direct Fulfillment Shipping
#The Selling Partner API for Direct Fulfillment Shipping provides programmatic access to a direct fulfillment vendor's shipping data.
OpenAPI spec version: v1
Generated by: https://github.com/swagger-api/swagger-codegen.git
Swagger Codegen version: 3.0.33
=end
require 'spec_helper'
require 'json'
require 'date'
# Unit tests for AmzSpApi::VendorDirectFulfillmentShippingApiModel::SubmitShipmentStatusUpdatesRequest
# Automatically generated by swagger-codegen (github.com/swagger-api/swagger-codegen)
# Please update as you see appropriate
describe 'SubmitShipmentStatusUpdatesRequest' do
before do
# run before each test
@instance = AmzSpApi::VendorDirectFulfillmentShippingApiModel::SubmitShipmentStatusUpdatesRequest.new
end
after do
# run after each test
end
describe 'test an instance of SubmitShipmentStatusUpdatesRequest' do
it 'should create an instance of SubmitShipmentStatusUpdatesRequest' do
expect(@instance).to be_instance_of(AmzSpApi::VendorDirectFulfillmentShippingApiModel::SubmitShipmentStatusUpdatesRequest)
end
end
describe 'test attribute "shipment_status_updates"' do
it 'should work' do
# assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers
end
end
end
| 32.780488 | 133 | 0.798363 |
d5c151e589587094b1db3b8d3d4f4d7693ba07a0 | 2,133 | # This file is auto-generated from the current state of the database. Instead
# of editing this file, please use the migrations feature of Active Record to
# incrementally modify your database, and then regenerate this schema definition.
#
# Note that this schema.rb definition is the authoritative source for your
# database schema. If you need to create the application database on another
# system, you should be using db:schema:load, not running all the migrations
# from scratch. The latter is a flawed and unsustainable approach (the more migrations
# you'll amass, the slower it'll run and the greater likelihood for issues).
#
# It's strongly recommended that you check this file into your version control system.
ActiveRecord::Schema.define(version: 2019_09_24_181411) do
# These are extensions that must be enabled in order to support this database
enable_extension "plpgsql"
create_table "repos", id: :bigint, default: nil, force: :cascade do |t|
t.bigint "github_repo_id"
t.string "name"
t.integer "forks_count"
t.integer "open_issues_count"
t.integer "percent_completion"
t.string "reason_a"
t.string "reason_b"
t.string "reason_c"
t.string "reason_d"
t.string "master_repo"
t.string "cohort_name"
end
create_table "repos_users", force: :cascade do |t|
t.bigint "repo_id"
t.bigint "user_id"
t.string "repo_name", limit: 255
t.string "github_username", limit: 255
t.string "user_cohort_name", limit: 255
end
create_table "surveys", force: :cascade do |t|
t.integer "repos_user_id"
t.string "completion_status"
t.string "incompleteReason"
t.string "issueType"
t.string "problemAnalysis"
t.string "suggestedFix"
t.string "github_username", limit: 255
t.string "master_repo", limit: 255
t.string "cohort_name", limit: 255
t.string "repo_name", limit: 255
end
create_table "users", force: :cascade do |t|
t.string "github_username"
t.string "username"
t.string "password_digest"
t.string "cohort_name"
t.string "role"
t.integer "karma"
t.string "avatar_url"
end
end
| 33.328125 | 86 | 0.72105 |
f7294f86a006cdd3b4a6debd22a3530aa7006745 | 793 | require_relative 'helper'
require_relative '../lib/day'
class TestDay < Minitest::Test
def test_initializing_a_day_saves_values
d = Day.new(05, 2015)
assert_equal 05, d.month
assert_equal 2015, d.year
end
def test_initializing_a_month_starting_on_sunday
d = Day.new(01, 2012)
assert_equal 1, d.day_of_week
end
def test_initializing_a_month_starting_on_tuesday
d = Day.new(04, 2014)
assert_equal 3, d.day_of_week
end
def test_initializing_a_month_starting_on_wednesday
d = Day.new(10, 2014)
assert_equal 4, d.day_of_week
end
def test_initializing_a_month_starting_on_friday
d = Day.new(03, 2013)
assert_equal 6, d.day_of_week
end
def test_jan_1_200
d = Day.new(1, 2000)
assert_equal 7, d.day_of_week
end
end
| 19.825 | 53 | 0.7314 |
edfc48c3bc9417586f1170d4baf0984a0a0326c7 | 126 | class CreateUser < ActiveRecord::Migration
def change
create_table :users do |t|
t.string :name
end
end
end
| 15.75 | 42 | 0.674603 |
1aff0937b5d35a0551b8e6ed133d4df2df8163f4 | 3,028 | module Provide
module Services
class Tourguide < Provide::ApiClient
def initialize(scheme = 'http', host, token)
@scheme = scheme
@host = host
@token = token
end
def directions(from_latitude, from_longitude, to_latitude, to_longitude, waypoints = nil, departure = 'now', alternatives = 0)
parse client.get('directions', {
:alternatives => alternatives,
:departure => departure,
:from_latitude => from_latitude,
:from_longitude => from_longitude,
:to_latitude => to_latitude,
:to_longitude => to_longitude,
:waypoints => waypoints,
})
end
def eta(from_latitude, from_longitude, to_latitude, to_longitude, waypoints = nil, departure = 'now', alternatives = 0)
parse client.get('directions/eta', {
:alternatives => alternatives,
:departure => departure,
:from_latitude => from_latitude,
:from_longitude => from_longitude,
:to_latitude => to_latitude,
:to_longitude => to_longitude,
:waypoints => waypoints,
})
end
def geocode(street_number = nil, street = nil, city = nil, state = nil, postal_code = nil)
parse client.get('geocoder', {
:street_number => street_number,
:street => street,
:city => city,
:state => state,
:postal_code => postal_code,
})
end
def reverse_geocode(latitude, longitude)
parse client.get('geocoder', {
:latitude => latitude,
:longitude => longitude,
})
end
def matrix(origin_coords, destination_coords)
parse client.get('matrix', {
:origin_coords => origin_coords,
:destination_coords => destination_coords,
})
end
def place_details(place_id)
parse client.get('places', {
:place_id => place_id,
})
end
def places_autocomplete(query, latitude, longitude, radius = 15, type = nil, components = nil)
params = {
:q => query,
:latitude => latitude,
:longitude => longitude,
:radius => radius,
}
params[:type] = type if type
params[:components] = components = components if components
parse client.get('places/autocomplete', params)
end
def timezones(latitude, longitude)
parse client.get('timezones', {
:latitude => latitude,
:longitude => longitude,
})
end
private
def client
@client ||= begin
Provide::ApiClient.new(@scheme, @host, 'api/v1/', @token)
end
end
def parse(response)
begin
body = response.code == 204 ? nil : JSON.parse(response.body)
return response.code, response.headers, body
rescue
raise Exception.new({
:code => response.code,
})
end
end
end
end
end
| 28.838095 | 132 | 0.560106 |
2686600fc617022f6f8d7e73eba61e9268da13e5 | 1,731 | # Basic implementation of a tagged logger that matches the API of
# ActiveSupport::TaggedLogging.
require 'logger'
module Kafka
class TaggedLogger < SimpleDelegator
%i(debug info warn error fatal).each do |method|
define_method method do |msg_or_progname, &block|
if block_given?
super(msg_or_progname, &block)
else
super("#{tags_text}#{msg_or_progname}")
end
end
end
def tagged(*tags)
new_tags = push_tags(*tags)
yield self
ensure
pop_tags(new_tags.size)
end
def push_tags(*tags)
tags.flatten.reject { |t| t.nil? || t.empty? }.tap do |new_tags|
current_tags.concat new_tags
end
end
def pop_tags(size = 1)
current_tags.pop size
end
def clear_tags!
current_tags.clear
end
def current_tags
# We use our object ID here to avoid conflicting with other instances
thread_key = @thread_key ||= "kafka_tagged_logging_tags:#{object_id}".freeze
Thread.current[thread_key] ||= []
end
def tags_text
tags = current_tags
if tags.any?
tags.collect { |tag| "[#{tag}] " }.join
end
end
def self.new(logger_or_stream = nil)
# don't keep wrapping the same logger over and over again
return logger_or_stream if logger_or_stream.is_a?(TaggedLogger)
super
end
def initialize(logger_or_stream = nil)
logger = if logger_or_stream.is_a?(::Logger)
logger_or_stream
elsif logger_or_stream
::Logger.new(logger_or_stream)
else
::Logger.new(nil)
end
super(logger)
end
def flush
clear_tags!
super if defined?(super)
end
end
end
| 22.480519 | 82 | 0.629694 |
6ab67f5fea535ecfeafc4de5234ac2167c968ff6 | 576 | # frozen_string_literal: true
# == Schema Information
#
# Table name: absences
#
# id :integer not null, primary key
# lesson_id :integer not null
# student_id :integer not null
#
# Indexes
#
# index_absences_on_lesson_id (lesson_id)
# index_absences_on_student_id (student_id)
#
# Foreign Keys
#
# fk_rails_... (lesson_id => lessons.id)
# fk_rails_... (student_id => students.id)
#
class Absence < ApplicationRecord
belongs_to :student
belongs_to :lesson
validates :student, uniqueness: {
scope: :lesson_id
}
end
| 19.862069 | 53 | 0.668403 |
1d165f43ecdf5166841f689c0f430a13566d172e | 9,495 | require "schema_to_scaffold"
module SchemaToScaffold
class CLI
TABLE_OPTIONS = "\nOptions are:\n4 for table 4; (4..6) for table 4 to 6; [4,6] for tables 4 and 6; * for all Tables"
def self.start(*args)
## Argument conditions
opts = parse_arguments(args)
if opts[:help]
puts Help.message
exit 0
end
## looking for /schema\S*.rb$/ in user directory
paths = Path.new(opts[:path])
path = paths.choose unless opts[:path].to_s.match(/\.rb$/)
## Opening file
path ||= opts[:path]
begin
data = File.open(path, 'r') { |f| f.read }
rescue
puts "\nUnable to open file '#{path}'"
exit 1
rescue Interrupt => e
exit 1
end
## Generate scripts from schema
schema = Schema.new(data)
schema_select_flag = opts[:output].nil?
auto_output_flag = ! schema_select_flag
begin
raise if schema.table_names.empty?
if schema_select_flag
puts "\nLoaded tables:"
schema.print_table_names
puts TABLE_OPTIONS
print "\nSelect a table: "
end
rescue
puts "Could not find tables in '#{path}'"
exit 1
end
#for auto-output default to *
if schema_select_flag
input = STDIN.gets.strip
else
input = "*"
end
begin
tables = schema.select_tables(input)
raise if tables.empty?
rescue
puts "Not a valid input. #{TABLE_OPTIONS}"
exit 1
rescue Interrupt => e
exit 1
end
target = opts[:factory_girl] ? "factory_girl:model" : "scaffold"
migration_flag = opts[:migration] ? true : false
skip_no_migration_flag = opts[:skip_no_migration] ? true : false
script = []
script_hash={}
#script_active_admin= [] #new:activeadmin
#script_graphql = [] #new:graphql-rails-generator
table_names = schema.table_names
known_tables = []
references_to_ignore = [ "CreatedBy", "UpdatedBy", "User", "Updator", "Creator", "created", "updated"]
tables.each do |table_id|
scaffold_data = generate_script(schema, table_id, target, migration_flag, skip_no_migration_flag)
activeadmin_data = generate_script_active_admin(schema, table_id) #new:activeadmin
graphql_data = generate_script_graphql_rails_generators(schema, table_id) #new:graphql-rails-generator
script << scaffold_data
script << activeadmin_data
script << graphql_data
script << "\n"
#script_active_admin << activeadmin_data
#script_graphql << graphql_data
table_name = table_names[table_id].camelize.singularize
known_tables << table_name
script_hash[table_name] = {
scaffold: scaffold_data, activeadmin: activeadmin_data, graphql_data: graphql_data,
references: (scaffold_data.join('').scan(/ (\w+):references/)).flatten.map{|x| x.camelize.singularize}.reject{|x| references_to_ignore.include? x}
}
#script_hash_references[table_name] = (scaffold_data.join('').scan(/ (\w+):references/)).flatten.map{|x| x.camelize.singularize}.reject{|x| [ "CreatedBy", "UpdatedBy"].include? x}
end
if auto_output_flag
output_sequence = []
seen_tables = []
seen_table_at = {}
resolve_level_count = 0
remaining_references = {}
script_hash_empty = !(script_hash.empty?)
while script_hash_empty
output_sequence << "\n\n# ************ RESOLVE LEVEL: #{resolve_level_count} **************\n\n"
puts "\n# resolve_level_count: #{resolve_level_count}\n"
puts "\n\nSeen Tables: #{seen_tables.sort.join(', ')}\n"
all_unresolved = true
script_hash.each do |table_name, gen_data|
references_for_table = gen_data[:references].reject{|x| !(known_tables.include? x)} #reject unknown tables
all_references = (gen_data[:scaffold].join('').scan(/ (\w+):references/)).flatten.map{|x| x.camelize.singularize}.reject{|x| references_to_ignore.include? x}
all_references_str = all_references.map{|x| (seen_table_at.key? x) ? [x, seen_table_at[x]] : [x,999] }.to_h.sort_by {|k,v| v}.to_h
if references_for_table.empty?
puts "creating #{table_name} base-table"
seen_tables << table_name
seen_table_at[table_name] = resolve_level_count
output_sequence << gen_data[:scaffold]
output_sequence << gen_data[:activeadmin]
output_sequence << gen_data[:graphql_data]
output_sequence << "# references: #{ all_references_str }"
output_sequence << "\n\n"
script_hash.delete(table_name)
all_unresolved = false
else
script_hash[table_name][:references] = references_for_table.reject{|x| seen_tables.include?(x) }
puts "#{references_for_table.count} unresolved: \t#{table_name} references:#{references_for_table }"
end
end
resolve_level_count += 1
if all_unresolved #|| resolve_level_count > 10
puts "\n\n\nError, missing some references (#{all_unresolved}).\n\nSeen Tables: #{seen_tables.sort.join(', ')}\n"
script_hash.each do |table_name, gen_data|
references_for_table = gen_data[:references].reject{|x| known_tables.include? x}
puts "#{references_for_table.count} unresolved: \t#{table_name} references:#{references_for_table}"
end
#exit(1)
#tack it on as is because screw it, what can you do?
script_hash.each do |table_name, gen_data|
all_references = (gen_data[:scaffold].join('').scan(/ (\w+):references/)).flatten.map{|x| x.camelize.singularize}.reject{|x| references_to_ignore.include? x}
all_references_str = all_references.map{|x| (seen_table_at.key? x) ? [x, seen_table_at[x]] : [x,999] }.to_h.sort_by {|k,v| v}.to_h
output_sequence << "# ****** WARNING: unresolved references *****\n\n"
output_sequence << gen_data[:scaffold]
output_sequence << gen_data[:activeadmin]
output_sequence << gen_data[:graphql_data]
output_sequence << "# references: #{ all_references_str }"
output_sequence << "\n\n"
end
#breakout
script_hash_empty= false
end
end
output = output_sequence.join("")
puts "\nScript for #{target}:\n\n"
puts output
else
output = script.join("")
#output_admin = script_active_admin.join(""); output += output_admin #new:activeadmin #new:activeadmin
#output_graphql = script_graphql.join(""); output += output_graphql #new:graphql-rails-generator
puts "\nScript for #{target}:\n\n"
puts output
end
if opts[:clipboard]
puts("\n(copied to your clipboard)")
Clipboard.new(output).command
end
if auto_output_flag
begin
output_filename = opts[:output_path]
default_output_dir = "output"
Dir.mkdir(default_output_dir) unless File.exists?(default_output_dir)
File.open(output_filename, "w") { |f| f.write output }
rescue
puts "\nUnable to write file '#{output_filename}'"
exit 1
rescue Interrupt => e
exit 1
end
end
end
##
# Parses ARGV and returns a hash of options.
def self.parse_arguments(argv)
if argv_index = argv.index("-p")
path = argv.delete_at(argv_index + 1)
output_path = "output/#{path}"
argv.delete('-p')
end
args = {
clipboard: argv.delete('-c'), # check for clipboard flag
factory_girl: argv.delete('-f'), # factory_girl instead of scaffold
migration: argv.delete('-m'), # generate migrations
skip_no_migration: argv.delete('-n'), # skip '--no-migration'
help: argv.delete('-h'), # check for help flag
output: argv.delete('-o'), # check for help flag
output_path: output_path, # check for help flag
path: path # get path to file(s)
}
if argv.empty?
args
else
puts "\n------\nWrong set of arguments.\n------\n"
puts Help.message
exit
end
end
##
# Generates the rails scaffold script
def self.generate_script(schema, table=nil, target, migration_flag, skip_no_migration_flag)
schema = Schema.new(schema) unless schema.is_a?(Schema)
return schema.to_script if table.nil?
schema.table(table).to_script(target, migration_flag, skip_no_migration_flag)
end
#new:activeadmin
def self.generate_script_active_admin(schema, table=nil)
schema = Schema.new(schema) unless schema.is_a?(Schema)
return schema.to_script_active_admin if table.nil?
schema.table(table).to_script_active_admin
end
#new:graphql-rails-generator
def self.generate_script_graphql_rails_generators(schema, table=nil)
schema = Schema.new(schema) unless schema.is_a?(Schema)
return schema.to_script_graphql_rails_generators if table.nil?
schema.table(table).to_script_graphql_rails_generators
end
end
end
| 37.529644 | 187 | 0.609584 |
6ac87150e259bc6ecc12deeba0298bdf1b5bcfd5 | 231 | class PostIndexSerializer < ActiveModel::Serializer
attributes :id, :track, :artists, :image, :preview, :description, :likes
has_many :comments, serializer: CommentsIndexSerializer
def likes
object.likes.count
end
end
| 25.666667 | 74 | 0.761905 |
6a4872e8a80b64c2ef1d7a7f90654798b96c78ee | 104 | module Stache
class Helper < Stache::Mustache::View
def url
h.stache_path
end
end
end
| 13 | 39 | 0.653846 |
6183c0030ccf6f89ffae4d08aafc3d6de73966f8 | 3,488 | #==============================================================================
# Vehicle Ports
# Version: 1.0.0
# Author: modern algebra (rmrk.net)
# Date: 29 December 2012
#++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
# Description:
#
# This script allows you to set it so that boats, ships, and airships, can
# only land in particular regions that you designate as ports for that type
# of vehicle. This allows you to, for instance, prevent ships from landing
# anywhere except at a dock, or boats from landing anywhere but on beaches or
# docks. It also works for airships, if you want to restrict the places that
# they can land.
#++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
# Instructions:
#
# Paste this script into its own slot in the Script Editor, above Main but
# below Materials.
#
# Beyond that, the only thing you need to do is go to the editable region at
# line 36 and input the IDs of any port regions into the array for each
# vehicle. By default, boats can land in regions 32 and 40, while ships can
# only land in region 40. Airship landing is unrestricted by default. You can
# change those values in the editable region.
#
# Once that is done, all you need to do to make a port is paint that tile
# with the port region for that vehicle.
#==============================================================================
$imported = {} unless $imported
$imported[:MA_VehiclePorts] = true
MAVP_PORT_REGIONS = {
#\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
# BEGIN Editable Region
#||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
# For each array, input the IDs of the regions in which the vehicle can land,
# separated by commas. If left empty, then that vehicle's landing locations are
# unrestricted and they can land no matter what the region.
boat: [32, 40], # IDs of regions in which a boat can land
ship: [40], # IDs of regions in which a ship can land
airship: [], # IDs of regions in which an airship can land
#||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
# END Editable Region
#//////////////////////////////////////////////////////////////////////////////
}
MAVP_PORT_REGIONS.default = []
#==============================================================================
# ** Game_Vehicle
#++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
# Summary of Changes:
# aliased method - land_ok?
#==============================================================================
class Game_Vehicle
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# * Determine if Docking/Landing Is Possible
# d: Direction (2,4,6,8)
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
alias mavp_landok_1up3 land_ok?
def land_ok?(x, y, d, *args)
unless MAVP_PORT_REGIONS[@type].empty? # Unless no port required
if @type == :airship
return false unless MAVP_PORT_REGIONS[@type].include?( $game_map.region_id(x, y) )
else
x2 = $game_map.round_x_with_direction(x, d)
y2 = $game_map.round_y_with_direction(y, d)
return false unless MAVP_PORT_REGIONS[@type].include?( $game_map.region_id(x2, y2) )
end
end
mavp_landok_1up3(x, y, d, *args) # Call original method
end
end | 46.506667 | 92 | 0.490539 |
abe5c88487724b22d194cc3a01dff2bb747e1f08 | 1,809 | # frozen_string_literal: true
#
# Copyright:: 2019, Chef Software Inc.
# Author:: Tim Smith (<[email protected]>)
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
module RuboCop
module Cop
module Chef
module ChefDeprecations
# The beta Audit Mode for Chef Infra Client was removed in Chef Infra Client 15.0. Users should instead use InSpec and the audit cookbook. See https://www.inspec.io/ for more information.
#
# @example
#
# # bad
# control_group 'Baseline' do
# control 'SSH' do
# it 'should be listening on port 22' do
# expect(port(22)).to be_listening
# end
# end
# end
class EOLAuditModeUsage < Base
MSG = 'The beta Audit Mode feature in Chef Infra Client was removed in Chef Infra Client 15.0. Users should instead use InSpec and the audit cookbook. See https://www.inspec.io/ for more information.'
RESTRICT_ON_SEND = [:control_group].freeze
def_node_matcher :control_group?, '(send nil? :control_group ...)'
def on_send(node)
control_group?(node) do
add_offense(node.loc.selector, message: MSG, severity: :warning)
end
end
end
end
end
end
end
| 35.470588 | 210 | 0.650083 |
ffd4db07730c64e60248224564468da36d1a52da | 1,831 | # This file is auto-generated from the current state of the database. Instead
# of editing this file, please use the migrations feature of Active Record to
# incrementally modify your database, and then regenerate this schema definition.
#
# Note that this schema.rb definition is the authoritative source for your
# database schema. If you need to create the application database on another
# system, you should be using db:schema:load, not running all the migrations
# from scratch. The latter is a flawed and unsustainable approach (the more migrations
# you'll amass, the slower it'll run and the greater likelihood for issues).
#
# It's strongly recommended that you check this file into your version control system.
ActiveRecord::Schema.define(version: 20170625220538) do
# These are extensions that must be enabled in order to support this database
enable_extension "plpgsql"
create_table "friendships", force: :cascade do |t|
t.integer "user_id"
t.integer "friend_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
create_table "messages", force: :cascade do |t|
t.string "subject", limit: 255
t.text "body"
t.integer "sender_id"
t.integer "recipient_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.boolean "is_read"
t.index ["recipient_id"], name: "index_messages_on_recipient_id"
t.index ["sender_id"], name: "index_messages_on_sender_id"
t.index ["subject"], name: "index_messages_on_subject"
end
create_table "users", force: :cascade do |t|
t.string "name", limit: 50
t.string "email", limit: 255
t.string "password_digest"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.index ["email"], name: "index_users_on_email"
end
end
| 38.145833 | 86 | 0.732387 |
38a9afd53d2d9d536b89566bca774c9fdc69f0d7 | 5,394 | # Copyright 2011-2012 Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"). You
# may not use this file except in compliance with the License. A copy of
# the License is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the "license" file accompanying this file. This file is
# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
# ANY KIND, either express or implied. See the License for the specific
# language governing permissions and limitations under the License.
require 'spec_helper'
module AWS
class EC2
describe InternetGateway do
let(:config) { stub_config }
let(:client) { config.ec2_client }
let(:internet_gateway) { InternetGateway.new('igw-123', :config => config) }
it_should_behave_like "an ec2 resource object"
context '#internet_gateway_id' do
it 'returns the internet gateway id passed in' do
internet_gateway.internet_gateway_id.should == 'igw-123'
end
it 'is aliased as #id' do
internet_gateway.id.should == internet_gateway.internet_gateway_id
end
end
context '#attach' do
it 'calls #attach_internet_gateway on the client' do
client.should_receive(:attach_internet_gateway).with(
:internet_gateway_id => internet_gateway.id,
:vpc_id => 'vpc-id')
internet_gateway.attach('vpc-id')
end
it 'accepts vpc objects' do
client.should_receive(:attach_internet_gateway).with(
:internet_gateway_id => internet_gateway.id,
:vpc_id => 'vpc-id')
internet_gateway.attach(VPC.new('vpc-id'))
end
end
context '#detach' do
it 'calls #detach_internet_gateway on the client' do
client.should_receive(:detach_internet_gateway).with(
:internet_gateway_id => internet_gateway.id,
:vpc_id => 'vpc-id')
internet_gateway.detach('vpc-id')
end
it 'accepts vpc objects' do
client.should_receive(:detach_internet_gateway).with(
:internet_gateway_id => internet_gateway.id,
:vpc_id => 'vpc-id')
internet_gateway.detach(VPC.new('vpc-id'))
end
end
context '#delete' do
it 'calls #delete_internet_gateway on the client' do
client.should_receive(:delete_internet_gateway).with(
:internet_gateway_id => internet_gateway.id)
internet_gateway.delete
end
end
context 'existing gateways' do
let(:response) { client.stub_for(:describe_internet_gateways) }
before(:each) do
response.data[:internet_gateway_set] = [
{
:internet_gateway_id => internet_gateway.id,
:vpc_id => 'vpc-id',
:attachment_set => [
{ :vpc_id => 'vpc-id', :state => 'attached' },
]
}
]
client.stub(:describe_internet_gateways).and_return(response)
end
context '#vpc' do
it 'returns the vpc' do
vpc = internet_gateway.vpc
vpc.should be_a(VPC)
vpc.vpc_id.should == 'vpc-id'
vpc.config.should == config
end
end
context '#vpc=' do
it 'attaches the gateway after detaching the previous vpc' do
client.should_receive(:detach_internet_gateway).with(
:internet_gateway_id => internet_gateway.id,
:vpc_id => 'vpc-id')
client.should_receive(:attach_internet_gateway).with(
:internet_gateway_id => internet_gateway.id,
:vpc_id => 'vpc-123')
internet_gateway.vpc = VPC.new('vpc-123')
end
end
context '#attachments' do
it 'returns an array of attachments' do
attachments = internet_gateway.attachments
attachments.size.should == 1
attachments[0].should be_an(InternetGateway::Attachment)
attachments[0].internet_gateway.should == internet_gateway
attachments[0].vpc.should == VPC.new('vpc-id', :config => config)
attachments[0].state.should == :attached
end
it 'calls detach when you delete an attahcment' do
client.should_receive(:detach_internet_gateway).with(
:internet_gateway_id => internet_gateway.id,
:vpc_id => 'vpc-id')
internet_gateway.attachments.first.delete
end
end
context '#exists?' do
it 'calls #describe_internet_gateways to determine if it exists' do
client.should_receive(:describe_internet_gateways).
with(:internet_gateway_ids => [internet_gateway.id]).
and_return(response)
internet_gateway.exists?
end
it 'returns true if it can be described' do
internet_gateway.exists?.should == true
end
it 'returns false if an error is raised trying to describe it' do
client.stub(:describe_internet_gateways).
and_raise(Errors::InvalidInternetGatewayID::NotFound.new('msg'))
internet_gateway.exists?.should == false
end
end
end
end
end
end
| 31 | 82 | 0.605858 |
03e3cf0512edd8ce2e10a53351cd56beac939358 | 511 | class ApplicationController < ActionController::Base
helper_method :current_user
def home
require_login
if current_user && !(current_user.username.present?)
current_user.username = current_user.email
end
end
def welcome
redirect_to home_path if user_signed_in?
end
def require_login
unless user_signed_in?
flash[:danger] = "You must be logged in to access this section!"
redirect_to root_path
end
end
end
| 21.291667 | 74 | 0.657534 |
6a5e547f1f49927490583e0f2f7f30f5fe68ac59 | 1,034 | # frozen_string_literal: true
# Copyright 2021 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# Auto-generated by gapic-generator-ruby. DO NOT EDIT!
require "gapic/rest"
require "google/cloud/compute/v1/ssl_certificates/rest/grpc_transcoding"
require "google/cloud/compute/v1/ssl_certificates/rest/client"
module Google
module Cloud
module Compute
module V1
module SslCertificates
# Client for the REST transport
module Rest
end
end
end
end
end
end
| 28.722222 | 74 | 0.731141 |
28518139164321129036b450fc464732a2d699a7 | 1,152 | class MovieTags < ActiveRecord::Migration
def self.up
# drop old tag tables
drop_table :tags
drop_table :taggings
create_table :categories do |t|
# parent tag
t.column :category_id, :int
end
create_table :movie_user_categories do |t|
t.column :category_id, :integer
t.column :movie_id, :integer
t.column :user_id, :integer
end
create_table :category_aliases do |t|
t.column :name, :string
t.column :language_id, :integer
t.column :page_id, :integer
end
end
def self.down
drop_table :categories
drop_table :category_aliases
drop_table :movie_user_categories
# recreate old tag tables
create_table :tags do |t|
t.column :name, :string, :limit => 24, :null => false
end
add_index :tags, [:name], :unique => true
create_table :taggings do |t|
t.column :tag_id, :integer, :null => false
t.column :taggable_id, :integer, :null => false
t.column :taggable_type, :string, :limit => 24, :null => false
end
add_index :taggings, [:taggable_type, :taggable_id], :unique => true
end
end
| 26.181818 | 72 | 0.638021 |
f893aaa18a0afc9acf9ea0a5afb9157fc7b8b937 | 591 | require "json"
package = JSON.parse(File.read(File.join(__dir__, "package.json")))
Pod::Spec.new do |s|
s.name = "leopard-react-native"
s.version = package["version"]
s.summary = package["description"]
s.homepage = package["homepage"]
s.license = package["license"]
s.authors = package["author"]
s.platforms = { :ios => "10.0" }
s.source = { :git => "https://github.com/Picovoice/leopard.git", :tag => "#{s.version}" }
s.source_files = "ios/*.{h,m,mm,swift}"
s.dependency "React"
s.dependency "Leopard-iOS", '~> 1.0.0'
end
| 28.142857 | 97 | 0.592217 |
1d5899ccc171c389f94fbee5437653a99f84b8be | 161 | class CreateActivities < ActiveRecord::Migration[5.2]
def change
create_table :activities do |t|
t.string :name
t.timestamps
end
end
end
| 17.888889 | 53 | 0.677019 |
1dbc4cc95ecb68382596f553aa5ea0ec4bfe86f2 | 832 | # frozen_string_literal: true
$LOAD_PATH.push File.expand_path('../lib', __FILE__)
# Maintain your gem's version:
require 'workarea/authorize_cim/version'
# Describe your gem and declare its dependencies:
Gem::Specification.new do |s|
s.name = 'workarea-authorize_cim'
s.version = Workarea::AuthorizeCim::VERSION
s.authors = ['Tom Scott']
s.email = ['[email protected]']
s.homepage = 'https://github.com/workarea-commerce/workarea-authorize_cim'
s.summary = 'Authorize.Net CIM Integration for WorkArea'
s.description = 'Authorize.Net CIM Integration for WorkArea'
s.files = `git ls-files`.split("\n")
s.license = 'Business Software License'
s.required_ruby_version = '>= 2.0.0'
s.add_dependency 'workarea', '~> 3.x'
s.add_development_dependency 'rubocop', '~> 0.49'
end
| 29.714286 | 79 | 0.698317 |
ac17b8c930f884be2757cc02c3f00527554f0bd2 | 3,662 | require "factory_girl_rails"
require "webmock/rspec"
require 'simplecov'
# Report to CodeClimate test coverage tool.
SimpleCov.start
RSpec.configure do |config|
# rspec-expectations config goes here. You can use an alternate
# assertion/expectation library such as wrong or the stdlib/minitest
# assertions if you prefer.
config.expect_with :rspec do |expectations|
# This option will default to `true` in RSpec 4. It makes the `description`
# and `failure_message` of custom matchers include text for helper methods
# defined using `chain`, e.g.:
# be_bigger_than(2).and_smaller_than(4).description
# # => "be bigger than 2 and smaller than 4"
# ...rather than:
# # => "be bigger than 2"
expectations.include_chain_clauses_in_custom_matcher_descriptions = true
end
# rspec-mocks config goes here. You can use an alternate test double
# library (such as bogus or mocha) by changing the `mock_with` option here.
config.mock_with :rspec do |mocks|
# Prevents you from mocking or stubbing a method that does not exist on
# a real object. This is generally recommended, and will default to
# `true` in RSpec 4.
mocks.verify_partial_doubles = true
end
# The settings below are suggested to provide a good initial experience
# with RSpec, but feel free to customize to your heart's content.
# # These two settings work together to allow you to limit a spec run
# # to individual examples or groups you care about by tagging them with
# # `:focus` metadata. When nothing is tagged with `:focus`, all examples
# # get run.
# config.filter_run :focus
# config.run_all_when_everything_filtered = true
#
# # Limits the available syntax to the non-monkey patched syntax that is recommended.
# # For more details, see:
# # - http://myronmars.to/n/dev-blog/2012/06/rspecs-new-expectation-syntax
# # - http://teaisaweso.me/blog/2013/05/27/rspecs-new-message-expectation-syntax/
# # - http://myronmars.to/n/dev-blog/2014/05/notable-changes-in-rspec-3#new__config_option_to_disable_rspeccore_monkey_patching
# config.disable_monkey_patching!
#
# # Many RSpec users commonly either run the entire suite or an individual
# # file, and it's useful to allow more verbose output when running an
# # individual spec file.
# if config.files_to_run.one?
# # Use the documentation formatter for detailed output,
# # unless a formatter has already been configured
# # (e.g. via a command-line flag).
# config.default_formatter = 'doc'
# end
#
# # Print the 10 slowest examples and example groups at the
# # end of the spec run, to help surface which specs are running
# # particularly slow.
# config.profile_examples = 10
#
# # Seed global randomization in this process using the `--seed` CLI option.
# # Setting this allows you to use `--seed` to deterministically reproduce
# # test failures related to randomization by passing the same `--seed` value
# # as the one that triggered the failure.
# Kernel.srand config.seed
# Suppress stdout and stderr while testing.
original_stderr = $stderr
original_stdout = $stdout
config.before(:all) do
# Redirect stderr and stdout
$stderr = File.new("/dev/null", "w")
$stdout = File.new("/dev/null", "w")
end
config.after(:all) do
$stderr = original_stderr
$stdout = original_stdout
end
# Enforce random ordering of tests
config.order = :random
# Configuration for testing
config.include FactoryGirl::Syntax::Methods
# Allow all unstubbed requests
WebMock.allow_net_connect!
end
| 40.688889 | 133 | 0.708356 |
4a70326c973c0e44c949ed4d02d7f1c7912d2191 | 158 | class Pattern < ActiveRecord::Base
belongs_to :user
has_many :needles
has_many :yarns
has_many :comments
validates_presence_of :name, :content
end
| 17.555556 | 39 | 0.765823 |
7a525f37b61037982c654366c746187780048cb3 | 38 | module Exonio
VERSION = "0.5.4"
end
| 9.5 | 19 | 0.657895 |
e2a70e47a7ac7c0834ee2e527351b5f51b599937 | 29 | # typed: true
if /wat/; end
| 7.25 | 13 | 0.586207 |
2158440d1ec2411f3b86e6af71acb5c30940f2ad | 234 | require File.expand_path('../../../../spec_helper', __FILE__)
require 'thread'
require File.expand_path('../../shared/queue/empty', __FILE__)
describe "Thread::Queue#empty?" do
it_behaves_like :queue_empty?, :empty?, Queue.new
end
| 29.25 | 62 | 0.717949 |
61a114d1b57a08e56b12f7b58c39d999fe4f64d1 | 364 | class Sparkle < Cask
version '1.8.0'
sha256 '882f2e414d2d8a3e776f9a9888cbfcb744df88f3b061325c2aad3c965af5ac1a'
url "https://github.com/sparkle-project/Sparkle/releases/download/#{version}/Sparkle-#{version}.tar.bz2"
appcast 'http://sparkle-project.org/files/sparkletestcast.xml'
homepage 'http://sparkle-project.org/'
link 'Sparkle Test App.app'
end
| 33.090909 | 106 | 0.771978 |
3919bbb14a5d006fae1fdd1bde82fb3d74614c95 | 364 | Rails.application.routes.draw do
root to: 'application#home'
resources :arrangements do
resources :orders, only: [:new, :index, :show, :create]
end
resources :users
get '/login', :to => 'sessions#new'
post '/sessions', :to => 'sessions#create'
get '/logout', :to => 'sessions#destroy'
get '/auth/github/callback' => 'sessions#create'
end
| 24.266667 | 59 | 0.656593 |
181bbeb99b2578ce7112822453bd93a719188a20 | 1,264 | module Ingenico::Connect::SDK
# Indicates that a payout is declined by the Ingenico ePayments platform or one of its downstream partners/acquirers.
class DeclinedPayoutException < DeclinedTransactionException
# Create a new DeclinedPayoutException.
# @see ApiException#initialize
def initialize(status_code, response_body, errors)
if errors.nil?
super(status_code, response_body, nil, nil, build_message(errors))
else
super(status_code, response_body, errors.error_id, errors.errors,
build_message(errors))
end
@errors = errors
end
# The declined payout result as returned by the Ingenico ePayments platform.
# Given as a {Ingenico::Connect::SDK::Domain::Payout::PayoutResult} object.
def payout_result
if @errors.nil?
nil
else
@errors.payout_result
end
end
private
def build_message(errors)
if !errors.nil?
payout = errors.payout_result
else
payout = nil
end
if payout.nil?
'the Ingenico ePayments platform returned a declined payout response'
else
"declined payment '" + payout.id + "' with status '" +
payout.status + "'"
end
end
end
end
| 28.088889 | 119 | 0.655854 |
bfa0f7c54c6cb3ed2e63b9162f6d0abdd7a1fa84 | 1,699 | # 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::Network::Mgmt::V2019_04_01
module Models
#
# Common error details representation.
#
class ErrorDetails
include MsRestAzure
# @return [String] Error code.
attr_accessor :code
# @return [String] Error target.
attr_accessor :target
# @return [String] Error message.
attr_accessor :message
#
# Mapper for ErrorDetails class as Ruby Hash.
# This will be used for serialization/deserialization.
#
def self.mapper()
{
client_side_validation: true,
required: false,
serialized_name: 'ErrorDetails',
type: {
name: 'Composite',
class_name: 'ErrorDetails',
model_properties: {
code: {
client_side_validation: true,
required: false,
serialized_name: 'code',
type: {
name: 'String'
}
},
target: {
client_side_validation: true,
required: false,
serialized_name: 'target',
type: {
name: 'String'
}
},
message: {
client_side_validation: true,
required: false,
serialized_name: 'message',
type: {
name: 'String'
}
}
}
}
}
end
end
end
end
| 24.623188 | 70 | 0.486168 |
4ab550505549a9cd3a98590901a7c012edb3013c | 1,211 | require 'helper'
class AddOutputTest < Test::Unit::TestCase
def setup
Fluent::Test.setup
end
CONFIG = %[
add_tag_prefix pre_hoge
<pair>
hoge moge
hogehoge mogemoge
</pair>
]
CONFIG_UU = %[
uuid true
<pair>
hoge moge
hogehoge mogemoge
</pair>
]
def create_driver(conf = CONFIG, tag='test')
Fluent::Test::OutputTestDriver.new(Fluent::AddOutput, tag).configure(conf)
end
def test_configure
d = create_driver
assert_equal 'pre_hoge', d.instance.config["add_tag_prefix"]
d = create_driver(CONFIG_UU)
assert d.instance.config["uuid"]
end
def test_format
d = create_driver
d.run do
d.emit("a" => 1)
end
mapped = {'hoge' => 'moge', 'hogehoge' => 'mogemoge'}
assert_equal [
{"a" => 1}.merge(mapped),
], d.records
d.run
end
def test_uu
d = create_driver(CONFIG_UU)
d.run do
d.emit("a" => 1)
end
assert d.records[0].has_key?('uuid')
d.run
end
def test_uuid_key
d = create_driver("#{CONFIG_UU}\nuuid_key test_uuid")
d.run do
d.emit("a" => 1)
end
assert d.records[0].has_key?('test_uuid')
d.run
end
end
| 17.550725 | 78 | 0.593724 |
1a21d7a8778031e5eb7f9a0b3daf0af19af04a02 | 428 | # frozen_string_literal: true
namespace :jira_connect do
# This is so we can have a named route helper for the base URL
root to: proc { [404, {}, ['']] }, as: 'base'
get 'app_descriptor' => 'app_descriptor#show'
get :users, to: 'users#show'
namespace :events do
post 'installed'
post 'uninstalled'
end
resources :subscriptions, only: [:index, :create, :destroy]
resources :branches, only: [:new]
end
| 23.777778 | 64 | 0.670561 |
1cf11d1b68393e3feb5b1101dddbdf3117193171 | 498 | # frozen_string_literal: true
class FiggyEventProcessor
attr_reader :event
def initialize(event)
@event = event
end
delegate :process, to: :processor
private
def event_type
event["event"]
end
def processor
case event_type
when "CREATED"
CreateProcessor.new(event)
when "UPDATED"
UpdateProcessor.new(event)
when "DELETED"
DeleteProcessor.new(event)
else
UnknownEvent.new(event)
end
end
end
| 16.6 | 35 | 0.634538 |
1c84b6c31b5a8518e68275dabc7878fa3c59ebe2 | 248 | require 'spec_helper'
def app
ApplicationApi
end
describe UsersApi do
include Rack::Test::Methods
describe 'e.g. GET, POST, PUT, etc.' do
it 'needs tests to be written!' do
pending('write tests for UsersApi!')
end
end
end
| 14.588235 | 42 | 0.677419 |
e8a105bf0b2c5ff79da1dda9b37f6410827a8856 | 749 | # frozen_string_literal: true
module Renalware
module UKRDC
module Outgoing
module Rendering
class LabOrders < Rendering::Base
pattr_initialize [:patient!]
def xml
lab_orders_element
end
private
def lab_orders_element
create_node("LabOrders") do |lab_orders|
lab_orders[:start] = patient.changes_since.to_date.iso8601
lab_orders[:stop] = patient.changes_up_until.to_date.iso8601
patient.observation_requests.each do |request|
lab_orders << Rendering::LabOrder.new(patient: patient, request: request).xml
end
end
end
end
end
end
end
end
| 24.16129 | 93 | 0.59012 |
bf6db1e17f50f31b86d2709ff01d4df37f1313cf | 969 | # This file is auto-generated from the current state of the database. Instead
# of editing this file, please use the migrations feature of Active Record to
# incrementally modify your database, and then regenerate this schema definition.
#
# Note that this schema.rb definition is the authoritative source for your
# database schema. If you need to create the application database on another
# system, you should be using db:schema:load, not running all the migrations
# from scratch. The latter is a flawed and unsustainable approach (the more migrations
# you'll amass, the slower it'll run and the greater likelihood for issues).
#
# It's strongly recommended that you check this file into your version control system.
ActiveRecord::Schema.define(version: 2020_06_15_170257) do
create_table "posts", force: :cascade do |t|
t.string "title"
t.text "description"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
end
| 42.130435 | 86 | 0.768834 |
1100b5f1b9d060232a453ce022f10e64b8e7fc50 | 74 | require 'ruby_box'
module RubyBox
class Error < StandardError
end
end | 12.333333 | 29 | 0.77027 |
624425fb6e031d8ae88a38de678b3560c653e538 | 127 | require 'rails_helper'
RSpec.describe Bartender, type: :model do
pending "add some examples to (or delete) #{__FILE__}"
end
| 21.166667 | 56 | 0.748031 |
1da3dde62201cccb5117e8fad30a29e952b8b69f | 2,181 | module Calculators
class DependantAllowanceCalculator
def self.call(dependant)
new(dependant).call
end
def initialize(dependant)
@dependant = dependant
end
def call
return child_under_15_allowance if under_15_years_old?
return child_under_16_allowance if under_16_years_old?
return under_18_in_full_time_education_allowance if under_18_in_full_time_education?
return 0.0 if capital_over_allowance?
positive_or_zero(adult_allowance - monthly_income)
end
def positive_or_zero(value)
[0, value].max
end
def child_under_16_allowance
positive_or_zero(child_aged_15_allowance - monthly_income)
end
def under_18_in_full_time_education_allowance
positive_or_zero(child_16_and_over_allowance - monthly_income)
end
def under_15_years_old?
@dependant.date_of_birth > (submission_date - 15.years)
end
def under_16_years_old?
@dependant.date_of_birth > (submission_date - 16.years)
end
def monthly_income
@dependant.monthly_income
end
def under_18_in_full_time_education?
@dependant.date_of_birth > (submission_date - 18.years) && @dependant.in_full_time_education?
end
def submission_date
@submission_date ||= assessment.submission_date
end
def assessment
@assessment ||= @dependant.assessment
end
def capital_over_allowance?
@dependant.assets_value > adult_dependant_allowance_capital_threshold
end
def child_under_15_allowance
Threshold.value_for(:dependant_allowances, at: submission_date)[:child_under_15]
end
def child_aged_15_allowance
Threshold.value_for(:dependant_allowances, at: submission_date)[:child_aged_15]
end
def child_16_and_over_allowance
Threshold.value_for(:dependant_allowances, at: submission_date)[:child_16_and_over]
end
def adult_allowance
Threshold.value_for(:dependant_allowances, at: submission_date)[:adult]
end
def adult_dependant_allowance_capital_threshold
Threshold.value_for(:dependant_allowances, at: submission_date)[:adult_capital_threshold]
end
end
end
| 25.964286 | 99 | 0.74553 |
ed00009928dfa656d6560d4435c7dc7ea8fb6e01 | 1,388 |
Pod::Spec.new do |s|
s.name = "UITableView+FDTemplateLayoutCell"
s.version = "1.6"
s.summary = "Template auto layout cell for automatically UITableViewCell height calculate, cache and precache"
s.description = "Template auto layout cell for automatically UITableViewCell height calculate, cache and precache. Requires a `self-satisfied` UITableViewCell, using system's `- systemLayoutSizeFittingSize:`, provides heights caching."
s.homepage = "https://github.com/forkingdog/UITableView-FDTemplateLayoutCell"
# ――― Spec License ――――――――――――――――――――――――――――――――――――――――――――――――――――――――――― #
s.license = { :type => "MIT", :file => "LICENSE" }
# ――― Author Metadata ――――――――――――――――――――――――――――――――――――――――――――――――――――――――― #
s.author = { "forkingdog group" => "https://github.com/forkingdog" }
# ――― Platform Specifics ――――――――――――――――――――――――――――――――――――――――――――――――――――――― #
s.platform = :ios, "6.0"
# ――― Source Location ―――――――――――――――――――――――――――――――――――――――――――――――――――――――――― #
s.source = { :git => "https://github.com/forkingdog/UITableView-FDTemplateLayoutCell.git", :tag => s.version.to_s }
# ――― Source Code ―――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――― #
s.source_files = "Classes/*.{h,m}"
# ――― Project Settings ――――――――――――――――――――――――――――――――――――――――――――――――――――――――― #
s.requires_arc = true
end
| 63.090909 | 238 | 0.505043 |
2195642e7329c41f802fb5257facca1f5ca30ba0 | 1,697 | require 'spec_helper'
require 'pawnee/base'
# NOTE: These are designed to run in order on vagrant
describe "user actions" do
before do
@base = Pawnee::Base.new
@base.destination_connection = VagrantManager.connect
end
def user_exists?(login)
_, _, exit_code, _ = @base.exec("id -u #{login}", :with_codes => true, :log_stderr => false)
return exit_code == 0
end
it "should create a user" do
@base.create_user(
name: 'Test Blue',
login: 'blue'
)
user_exists?('blue').should == true
end
it "should shouldn't recreate a user" do
@base.should_receive(:say_status).with(:user_exists, 'blue', :blue)
@base.create_user(
name: 'Test Blue',
login: 'blue'
)
end
it "should modify a user" do
# @base.should_receive(:exec).any_number_of_times.ordered.with('id -u blue', :with_codes => true).and_return(["1002\n", '', 0, nil])
# @base.should_receive(:exec).any_number_of_times.ordered.with('id -u blue', :with_codes => true).and_return(["1002\n", '', 0, nil])
# @base.should_receive(:exec).any_number_of_times.ordered.with('id -g blue').and_return("1002\n")
# @base.should_receive(:exec).any_number_of_times.ordered.with('groups blue').and_return("blue: blue")
# @base.should_receive(:exec).once.ordered.with('useradd -c "comment" blue').and_return('')
@base.create_user(
name: 'Test Blue',
login: 'blue',
comment: 'comment'
)
end
# TODO: Test when there is no groups
# TODO: Test default shell
it "should delete a user" do
user_exists?('blue').should == true
@base.delete_user('blue')
user_exists?('blue').should == false
end
end | 29.77193 | 136 | 0.645256 |
bf41654ab2ed51ddafb2b60f15061fd64a436176 | 7,983 | require 'test_helper'
class RemoteGlobalCollectTest < Test::Unit::TestCase
def setup
@gateway = GlobalCollectGateway.new(fixtures(:global_collect))
@amount = 100
@credit_card = credit_card('4567350000427977')
@declined_card = credit_card('5424180279791732')
@accepted_amount = 4005
@rejected_amount = 2997
@options = {
email: '[email protected]',
billing_address: address,
description: 'Store Purchase'
}
end
def test_successful_purchase
response = @gateway.purchase(@accepted_amount, @credit_card, @options)
assert_success response
assert_equal 'Succeeded', response.message
assert_equal 'CAPTURE_REQUESTED', response.params['payment']['status']
end
def test_successful_purchase_with_fraud_fields
options = @options.merge(
fraud_fields: {
'website' => 'www.example.com',
'giftMessage' => 'Happy Day!'
}
)
response = @gateway.purchase(@amount, @credit_card, options)
assert_success response
assert_equal 'Succeeded', response.message
end
def test_successful_purchase_with_more_options
options = @options.merge(
order_id: '1',
ip: '127.0.0.1',
email: '[email protected]',
sdk_identifier: 'Channel',
sdk_creator: 'Bob',
integrator: 'Bill',
creator: 'Super',
name: 'Cala',
version: '1.0',
extension_ID: '5555555'
)
response = @gateway.purchase(@amount, @credit_card, options)
assert_success response
assert_equal 'Succeeded', response.message
end
def test_successful_purchase_with_installments
options = @options.merge(number_of_installments: 2)
response = @gateway.purchase(@amount, @credit_card, options)
assert_success response
assert_equal 'Succeeded', response.message
end
# When requires_approval is true (or not present),
# `purchase` will make both an `auth` and a `capture` call
def test_successful_purchase_with_requires_approval_true
options = @options.merge(requires_approval: true)
response = @gateway.purchase(@amount, @credit_card, options)
assert_success response
assert_equal 'Succeeded', response.message
assert_equal 'CAPTURE_REQUESTED', response.params['payment']['status']
end
# When requires_approval is false, `purchase` will only make an `auth` call
# to request capture (and no subsequent `capture` call).
def test_successful_purchase_with_requires_approval_false
options = @options.merge(requires_approval: false)
response = @gateway.purchase(@amount, @credit_card, options)
assert_success response
assert_equal 'Succeeded', response.message
assert_equal 'CAPTURE_REQUESTED', response.params['payment']['status']
end
def test_successful_purchase_with_airline_data
options = @options.merge(
airline_data: {
code: 111,
name: 'Spreedly Airlines',
flight_date: '20190810',
passenger_name: 'Randi Smith',
flight_legs: [
{ arrival_airport: 'BDL',
origin_airport: 'RDU',
date: '20190810',
carrier_code: 'SA',
number: 596,
airline_class: 'ZZ'},
{ arrival_airport: 'RDU',
origin_airport: 'BDL',
date: '20190817',
carrier_code: 'SA',
number: 597,
airline_class: 'ZZ'}
]
}
)
response = @gateway.purchase(@amount, @credit_card, options)
assert_success response
assert_equal 'Succeeded', response.message
end
def test_failed_purchase_with_insufficient_airline_data
options = @options.merge(
airline_data: {
flight_date: '20190810',
passenger_name: 'Randi Smith'
}
)
response = @gateway.purchase(@amount, @credit_card, options)
assert_failure response
assert_equal 'PARAMETER_NOT_FOUND_IN_REQUEST', response.message
property_names = response.params['errors'].collect { |e| e['propertyName'] }
assert property_names.include? 'order.additionalInput.airlineData.code'
assert property_names.include? 'order.additionalInput.airlineData.name'
end
def test_successful_purchase_with_very_long_name
credit_card = credit_card('4567350000427977', { first_name: 'thisisaverylongfirstname'})
response = @gateway.purchase(@amount, credit_card, @options)
assert_success response
assert_equal 'Succeeded', response.message
end
def test_successful_purchase_with_blank_name
credit_card = credit_card('4567350000427977', { first_name: nil, last_name: nil})
response = @gateway.purchase(@amount, credit_card, @options)
assert_success response
assert_equal 'Succeeded', response.message
end
def test_failed_purchase
response = @gateway.purchase(@rejected_amount, @declined_card, @options)
assert_failure response
assert_equal 'Not authorised', response.message
end
def test_successful_authorize_and_capture
auth = @gateway.authorize(@amount, @credit_card, @options)
assert_success auth
assert capture = @gateway.capture(@amount, auth.authorization, @options)
assert_success capture
assert_equal 'Succeeded', capture.message
end
def test_failed_authorize
response = @gateway.authorize(@amount, @declined_card, @options)
assert_failure response
assert_equal 'Not authorised', response.message
end
def test_partial_capture
auth = @gateway.authorize(@amount, @credit_card, @options)
assert_success auth
assert capture = @gateway.capture(@amount - 1, auth.authorization)
assert_success capture
assert_equal 99, capture.params['payment']['paymentOutput']['amountOfMoney']['amount']
end
def test_failed_capture
response = @gateway.capture(@amount, '123', @options)
assert_failure response
assert_match %r{UNKNOWN_PAYMENT_ID}, response.message
end
# Because payments are not fully authorized immediately, refunds can only be
# tested on older transactions (~24hrs old should be fine)
#
# def test_successful_refund
# txn = REPLACE WITH PREVIOUS TRANSACTION AUTHORIZATION
#
# assert refund = @gateway.refund(@accepted_amount, txn)
# assert_success refund
# assert_equal 'Succeeded', refund.message
# end
#
# def test_partial_refund
# txn = REPLACE WITH PREVIOUS TRANSACTION AUTHORIZATION
#
# assert refund = @gateway.refund(@amount-1, REPLACE WITH PREVIOUS TRANSACTION AUTHORIZATION)
# assert_success refund
# end
def test_failed_refund
response = @gateway.refund(@amount, '123')
assert_failure response
assert_match %r{UNKNOWN_PAYMENT_ID}, response.message
end
def test_successful_void
auth = @gateway.authorize(@amount, @credit_card, @options)
assert_success auth
assert void = @gateway.void(auth.authorization)
assert_success void
assert_equal 'Succeeded', void.message
end
def test_failed_void
response = @gateway.void('123')
assert_failure response
assert_match %r{UNKNOWN_PAYMENT_ID}, response.message
end
def test_successful_verify
response = @gateway.verify(@credit_card, @options)
assert_success response
assert_equal 'Succeeded', response.message
end
def test_failed_verify
response = @gateway.verify(@declined_card, @options)
assert_failure response
assert_equal 'Not authorised', response.message
end
def test_invalid_login
gateway = GlobalCollectGateway.new(merchant_id: '', api_key_id: '', secret_api_key: '')
response = gateway.purchase(@amount, @credit_card, @options)
assert_failure response
assert_match %r{MISSING_OR_INVALID_AUTHORIZATION}, response.message
end
def test_transcript_scrubbing
transcript = capture_transcript(@gateway) do
@gateway.purchase(@amount, @credit_card, @options)
end
transcript = @gateway.scrub(transcript)
assert_scrubbed(@credit_card.number, transcript)
assert_scrubbed(@gateway.options[:secret_api_key], transcript)
end
end
| 31.678571 | 97 | 0.712013 |
1a7eb769b8201a37538ca8771c990e0f4b5a033e | 366 | module ApplicationHelper
def controller?(*controller)
controller.include?(params[:controller])
end
def action?(*action)
action.include?(params[:action])
end
def nav_link(link_text, link_path)
class_name = current_page?(link_path) ? 'active' : ''
content_tag(:li, :class => class_name) do
link_to link_text, link_path
end
end
end
| 17.428571 | 55 | 0.696721 |
ac012ac79967cd597e8d5d35aebafd44b34e39b5 | 536 | ENV['RACK_ENV'] = 'test'
require("bundler/setup")
Bundler.require(:default, :test)
Dir[File.dirname(__FILE__) + '/../lib/*.rb'].each { |file| require file }
require("bundler/setup")
Bundler.require(:default, :test)
set(:root, Dir.pwd())
require('capybara/rspec')
Capybara.app = Sinatra::Application
set(:show_exceptions, false)
require('./app')
RSpec.configure do |config|
config.after(:each) do
Band.all().each() do |band|
band.destroy()
end
Venue.all().each() do |venue|
venue.destroy()
end
end
end
| 19.851852 | 73 | 0.660448 |
ab429ccee2ec0313185c6130f3bd9a73909a2fa7 | 3,182 | #-- encoding: UTF-8
#-- copyright
# OpenProject is a project management system.
# Copyright (C) 2012-2018 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-2017 Jean-Philippe Lang
# Copyright (C) 2010-2013 the ChiliProject Team
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# See docs/COPYRIGHT.rdoc for more details.
#++
class Activity::WorkPackageActivityProvider < Activity::BaseActivityProvider
acts_as_activity_provider type: 'work_packages',
permission: :view_work_packages
def extend_event_query(query, activity)
query.join(types_table).on(activity_journals_table(activity)[:type_id].eq(types_table[:id]))
query.join(statuses_table).on(activity_journals_table(activity)[:status_id].eq(statuses_table[:id]))
end
def event_query_projection(activity)
[
activity_journal_projection_statement(:subject, 'subject', activity),
activity_journal_projection_statement(:project_id, 'project_id', activity),
projection_statement(statuses_table, :name, 'status_name'),
projection_statement(statuses_table, :is_closed, 'status_closed'),
projection_statement(types_table, :name, 'type_name')
]
end
def self.work_package_title(id, subject, type_name, status_name, is_standard)
title = "#{(is_standard) ? '' : "#{type_name}"} ##{id}: #{subject}"
title << " (#{status_name})" unless status_name.blank?
end
protected
def event_title(event, _activity)
self.class.work_package_title(event['journable_id'],
event['subject'],
event['type_name'],
event['status_name'],
event['is_standard'])
end
def event_type(event, _activity)
state = ActiveRecord::Type::Boolean.new.cast(event['status_closed']) ? '-closed' : '-edit'
"work_package#{state}"
end
def event_path(event, _activity)
url_helpers.work_package_path(event['journable_id'])
end
def event_url(event, _activity)
url_helpers.work_package_url(event['journable_id'],
anchor: notes_anchor(event))
end
private
def notes_anchor(event)
version = event['version'].to_i
(version > 1) ? "note-#{version - 1}" : ''
end
end
| 36.574713 | 104 | 0.694846 |
180956d8bf2b25495d6142249e2a9a96d7e77033 | 427 | cask :v1 => 'bootxchanger' do
version '2.0'
sha256 'cfb05680ab6a7d0b1793a33135dd15562a7b5fd59bb1ebf3ad6067c2c9fad6c1'
url "http://namedfork.net/_media/bootxchanger_#{version}.dmg"
appcast 'http://swupdate.namedfork.net/bootxchanger.xml',
:sha256 => 'afbae3b2a378ebb18f1668c062ba48436e956cad840fcc86cba610d351931187'
homepage 'http://namedfork.net/bootxchanger'
license :gpl
app 'BootXChanger.app'
end
| 32.846154 | 87 | 0.772834 |
6a9f6793ef909a6889959832bd0b7548c13f3541 | 3,597 | require 'spec_helper'
require 'pp'
# I have to do a bunch of shenanigans to get the stuff to load in order ot test
# require_relative '../../../stash_engine/app/serializers/stash_engine/serializer_mixin'
SERIAL_PATH = StashEngine::Engine.root.join('app/serializers/stash_engine')
$LOAD_PATH.unshift(SERIAL_PATH)
require 'serializer_mixin'
# define this class so I can mock it if it's not defined
unless defined?(Doorkeeper)
module Doorkeeper
class Application
end
end
end
# Sorry, I put the serializers for doing a DB serialization for migration into StashEngine, but the test is here.
# I didn't think through that the tests here have both engines, but StashEngine doesn't have Datacite metadata.
# I don't really want to move the serializer "models" around now and it's for a one time export on a codebase that will likely
# be thrown away in a couple months, so I don't have a lot of motivation to spend my time reorganizing for purity.
#
# I think this will do for now, even though it crosses engines and the scope isn't really quite right.
describe StashDatacite do
describe 'Serialization' do
before(:each) do
# needed because of bad column names set somehow in ActiveRecord
ActiveRecord::Base.descendants.each(&:reset_column_information)
allow(Doorkeeper::Application).to receive(:column_names).and_return(%w[id name uid secret redirect_uri scopes
created_at updated_at owner_id owner_type confidential])
allow(Doorkeeper::Application).to receive(:where).with(owner_id: 299).and_return([])
Dir.glob("#{SERIAL_PATH}/*.rb").each(&method(:require))
# load a sample file for fixure data for a rough test,
# This is based on a real data record which was easier to export from our database intact that generate full factories
# for a large number of models
my_queries = File.read(StashDatacite::Engine.root.join('spec', 'fixtures', 'full_record_for_export.sql')).split("\n\n")
my_queries.each do |q|
next if q.start_with?('--')
ActiveRecord::Base.connection.execute(q)
end
# needed because of bad column names set somehow in ActiveRecord
ActiveRecord::Base.descendants.each(&:reset_column_information)
tenant = { full_domain: 'test.dash.org' }.to_ostruct
allow(StashEngine::Tenant).to receive(:find).with('ucop').and_return(tenant)
end
it 'serializes a full record' do
my_id = StashEngine::Identifier.find(327)
hash = StashEngine::StashIdentifierSerializer.new(my_id).hash
expect_hash = JSON.parse(File.read(StashDatacite::Engine.root.join('spec', 'data', 'migration_output.json')))
# everything but resources since it's a mega hash and easier to see errors when only small bits are compared instead of mega hash
expect_hash.keys.reject! { |i| i == 'resources' }.each do |key|
expect(hash[key].to_json).to eq(expect_hash[key].to_json),
"expected #{key} to eq #{expect_hash[key].to_json}, got #{hash[key].to_json}"
end
expect_hash['resources'].each_with_index do |expect_resource, idx|
expect_resource.keys.each do |key|
expect(hash['resources'][idx][key].to_json).to eq(expect_resource[key].to_json),
"expected #{idx}:#{key} to eq #{expect_resource[key].to_json}, " \
" got #{hash['resources'][idx][key].to_json}"
end
end
end
end
end
| 47.96 | 135 | 0.674173 |
6226301142125bd6bcac84847a6f9ad5c0694a15 | 1,661 | require 'spec_helper'
require 'albacore/plink'
describe PLink, 'when executing a command over plink' do
before :each do
@cmd = PLink.new
@cmd.extend(SystemPatch)
@cmd.extend(FailPatch)
@cmd.command ="C:\\plink.exe"
@cmd.host = "testhost"
end
it "should attempt to execute plink.exe" do
@cmd.run
@cmd.system_command.should include("plink.exe")
end
it "should attempt to connect to the test host on the default port (22)" do
@cmd.run
@cmd.system_command.should include("@testhost")
@cmd.system_command.should include("-P 22")
end
it "should connect to the test host on a non default port 2200" do
@cmd.port = 2200
@cmd.run
@cmd.system_command.should include("-P 2200")
end
it "should connect to the host with a username" do
expected_user = "dummyuser"
@cmd.user = expected_user
@cmd.run
@cmd.system_command.should include("#{expected_user}@")
end
it "should run remote commands in batch mode" do
@cmd.run
@cmd.system_command.should include("-batch")
end
it "should run commands in verbose mode" do
@cmd.verbose = true
@cmd.run
@cmd.system_command.should include("-v")
end
it "should include the remote command" do
expected_remote_exe = "C:\ThisIsTheRemoteExe.exe"
@cmd.commands expected_remote_exe
@cmd.run
@cmd.system_command.should include(expected_remote_exe)
end
it "should include the remote command with parameters" do
expected_remote_exe = "C:\\ThisIsTheRemoteExe.exe --help -o -p"
@cmd.commands expected_remote_exe
@cmd.run
@cmd.system_command.should include(expected_remote_exe)
end
end
| 26.365079 | 78 | 0.695364 |
edf07e4e5ace75a07464bf40658e0319b729426f | 1,502 | =begin
#Fatture in Cloud API v2 - API Reference
#Connect your software with Fatture in Cloud, the invoicing platform chosen by more than 400.000 businesses in Italy. The Fatture in Cloud API is based on REST, and makes possible to interact with the user related data prior authorization via OAuth2 protocol.
The version of the OpenAPI document: 2.0.7
Contact: [email protected]
Generated by: https://openapi-generator.tech
OpenAPI Generator version: 5.3.0
=end
require 'spec_helper'
require 'json'
require 'date'
# Unit tests for FattureInCloud_Ruby_Sdk::CreateCashbookEntryRequest
# Automatically generated by openapi-generator (https://openapi-generator.tech)
# Please update as you see appropriate
describe FattureInCloud_Ruby_Sdk::CreateCashbookEntryRequest do
instance = FattureInCloud_Ruby_Sdk::CreateCashbookEntryRequest.new
instance.data = {
date: Date.new(2021, 12, 21),
amount_in: 122.0,
payment_account_in: {
id: 333
},
description: "Fattura n. 201/2021",
entity_name: "Rossi S.r.l.",
kind: "issued_document",
document: {
id: 54321
},
type: "in"
}
describe 'test an instance of CreateCashbookEntryRequest' do
it 'should create an instance of CreateCashbookEntryRequest' do
expect(instance).to be_instance_of(FattureInCloud_Ruby_Sdk::CreateCashbookEntryRequest)
end
end
describe 'test attribute "data"' do
it 'should work' do
expect(instance.data).to be_a_kind_of(Object)
end
end
end
| 30.653061 | 261 | 0.745672 |
4a87b0f37ff7551a2b904bfdb23bbf54b5fb4ba1 | 1,970 | Sequel.migration do
up do
alter_table :apps_routes do
# mysql requires foreign key to be dropped before index
drop_foreign_key [:app_id], name: :fk_apps_routes_app_id
drop_foreign_key [:route_id], name: :fk_apps_routes_route_id
drop_index [:app_id, :route_id], name: :ar_app_id_route_id_index
add_foreign_key [:app_id], :apps, name: :fk_apps_routes_app_id
add_foreign_key [:route_id], :routes, name: :fk_apps_routes_route_id
add_primary_key :id
add_column :created_at, :timestamp, null: false, default: Sequel::CURRENT_TIMESTAMP
add_column :updated_at, :timestamp
add_column :app_port, Integer
add_column :guid, String
end
if self.class.name.match?(/mysql/i)
run 'update apps_routes set guid=UUID();'
elsif self.class.name.match?(/postgres/i)
run 'CREATE OR REPLACE FUNCTION get_uuid()
RETURNS TEXT AS $$
BEGIN
BEGIN
RETURN gen_random_uuid();
EXCEPTION WHEN OTHERS THEN
RETURN uuid_generate_v4();
END;
END;
$$ LANGUAGE plpgsql;'
run 'update apps_routes set guid=get_uuid();'
end
alter_table :apps_routes do
add_index :guid, unique: true, name: :apps_routes_guid_index
add_index :created_at, name: :apps_routes_created_at_index
add_index :updated_at, name: :apps_routes_updated_at_index
end
end
down do
alter_table :apps_routes do
drop_index :guid, name: :apps_routes_guid_index
drop_index :updated_at, name: :apps_routes_updated_at_index
drop_index :created_at, name: :apps_routes_created_at_index
drop_column :guid
drop_column :app_port
drop_column :updated_at
drop_column :created_at
drop_column :id
add_index [:app_id, :route_id], unique: true, name: :ar_app_id_route_id_index
end
if self.class.name.match?(/postgres/i)
run 'drop function if exists get_uuid();'
end
end
end
| 31.269841 | 89 | 0.688325 |
bf4d652692fa48d52fbcafcb5d8c464e61e720ca | 13,996 | Given(/^Multiple Conversion Employers for (.*) exist with active and renewing plan years$/) do |named_person|
person = people[named_person]
secondary_organization = FactoryGirl.create :organization, legal_name: person[:mlegal_name],
dba: person[:mdba],
fein: person[:mfein]
secondary_employer_profile = FactoryGirl.create :employer_profile, organization: secondary_organization,
profile_source:'conversion',
registered_on: TimeKeeper.date_of_record
secondary_employee = FactoryGirl.create :census_employee, employer_profile: secondary_employer_profile,
first_name: person[:first_name],
last_name: person[:last_name],
ssn: person[:ssn],
dob: person[:dob_date]
open_enrollment_start_on = TimeKeeper.date_of_record
open_enrollment_end_on = open_enrollment_start_on.end_of_month + 13.days
start_on = open_enrollment_end_on.next_month.beginning_of_month
end_on = start_on + 1.year - 1.day
active_plan_year = FactoryGirl.create :plan_year, employer_profile: secondary_employer_profile,
start_on: start_on - 1.year,
end_on: end_on - 1.year,
open_enrollment_start_on: open_enrollment_start_on - 1.year,
open_enrollment_end_on: open_enrollment_end_on - 1.year - 3.days,
fte_count: 2,
aasm_state: :published,
is_conversion: true
secondary_benefit_group = FactoryGirl.create :benefit_group, plan_year: active_plan_year
secondary_employee.add_benefit_group_assignment secondary_benefit_group, secondary_benefit_group.start_on
renewing_plan_year = FactoryGirl.create :plan_year, employer_profile: secondary_employer_profile,
start_on: start_on,
end_on: end_on,
open_enrollment_start_on: open_enrollment_start_on,
open_enrollment_end_on: open_enrollment_end_on,
fte_count: 2,
aasm_state: :renewing_enrolling
benefit_group = FactoryGirl.create :benefit_group, plan_year: renewing_plan_year, title: 'this is the BGGG'
secondary_employee.add_renew_benefit_group_assignment benefit_group
FactoryGirl.create(:qualifying_life_event_kind, market_kind: "shop")
end
Then(/Employee (.*) should have the (.*) plan year start date as earliest effective date/) do |named_person, plan_year|
person = people[named_person]
employer_profile = EmployerProfile.find_by_fein(person[:fein])
census_employee = employer_profile.census_employees.where(first_name: person[:first_name], last_name: person[:last_name]).first
bg = plan_year == "renewing" ? census_employee.renewal_benefit_group_assignment.benefit_group : census_employee.active_benefit_group_assignment.benefit_group
if bg.effective_on_for(census_employee.hired_on) == employer_profile.renewing_plan_year.start_on
else
expect(page).to have_content "Raising this failure, b'coz this else block should never be executed"
end
end
Then(/Employee (.*) should not see earliest effective date on the page/) do |named_person|
person = people[named_person]
employer_profile = EmployerProfile.find_by_fein(person[:fein])
expect(page).not_to have_content "coverage starting #{employer_profile.renewing_plan_year.start_on.strftime("%m/%d/%Y")}."
end
And(/(.*) already matched and logged into employee portal/) do |named_person|
person = people[named_person]
employer_profile = EmployerProfile.find_by_fein(person[:fein])
ce = employer_profile.census_employees.where(:first_name => /#{person[:first_name]}/i,
:last_name => /#{person[:last_name]}/i).first
person_record = FactoryGirl.create(:person_with_employee_role, first_name: person[:first_name],
last_name: person[:last_name],
ssn: person[:ssn],
dob: person[:dob_date],
census_employee_id: ce.id,
employer_profile_id: employer_profile.id,
hired_on: ce.hired_on)
ce.update_attributes(employee_role_id: person_record.employee_roles.first.id)
FactoryGirl.create :family, :with_primary_family_member, person: person_record
user = FactoryGirl.create(:user, person: person_record,
email: person[:email],
password: person[:password],
password_confirmation: person[:password])
login_as user
visit "/families/home"
end
And(/(.*) matches all employee roles to employers and is logged in/) do |named_person|
person = people[named_person]
organizations = Organization.in(fein: [person[:fein], person[:mfein]])
employer_profiles = organizations.map(&:employer_profile)
counter = 0
used_person = nil
user = nil
employer_profiles.each do |employer_profile|
if used_person.nil?
ce = employer_profile.census_employees.where(:first_name => /#{person[:first_name]}/i,
:last_name => /#{person[:last_name]}/i).first
person_record = FactoryGirl.create(:person_with_employee_role, first_name: person[:first_name],
last_name: person[:last_name],
ssn: person[:ssn],
dob: person[:dob_date],
census_employee_id: ce.id,
employer_profile_id: employer_profile.id,
hired_on: ce.hired_on)
FactoryGirl.create :family, :with_primary_family_member, person: person_record
user = FactoryGirl.create(:user, person: person_record,
email: person[:email],
password: person[:password],
password_confirmation: person[:password])
used_person = person_record
else
ce = employer_profile.census_employees.where(:first_name => /#{person[:first_name]}/i,
:last_name => /#{person[:last_name]}/i).first
used_person.employee_roles.create!(employer_profile_id: employer_profile.id,
ssn: ce.ssn,
dob: ce.dob,
hired_on: ce.hired_on,
census_employee_id: ce.id)
end
end
login_as used_person.user
expect(used_person.employee_roles.count).to eq(2)
visit "/families/home"
end
Then(/Employee should see \"employer-sponsored benefits not found\" error message/) do
screenshot("new_hire_not_yet_eligible_exception")
find('.alert', text: "Unable to find employer-sponsored benefits for enrollment year")
visit '/families/home'
end
Then(/Employee should see \"You are attempting to purchase coverage through qle proir to your eligibility date\" error message/) do
screenshot("new_hire_not_yet_eligible_exception")
find('.alert', text: "You are attempting to purchase coverage through Qualifying Life Event prior to your eligibility date")
visit '/families/home'
end
And(/Employer for (.*) published renewing plan year/) do |named_person|
person = people[named_person]
employer_profile = EmployerProfile.find_by_fein(person[:fein])
employer_profile.renewing_plan_year.update_attributes(:aasm_state => 'renewing_published')
end
And(/Employer for (.*) is under open enrollment/) do |named_person|
person = people[named_person]
employer_profile = EmployerProfile.find_by_fein(person[:fein])
employer_profile.renewing_plan_year.update_attributes(:aasm_state => 'renewing_enrolling', open_enrollment_start_on: TimeKeeper.date_of_record.beginning_of_month)
end
And(/Other Employer for (.*) is also under open enrollment/) do |named_person|
person = people[named_person]
employer_profile = EmployerProfile.find_by_fein(person[:mfein])
employer_profile.renewing_plan_year.update_attributes(:aasm_state => 'renewing_enrolling', :open_enrollment_start_on => TimeKeeper.date_of_record)
end
When(/Employee clicks on New Hire Badge/) do
find('#shop_for_employer_sponsored_coverage').click
end
When(/(.*) has New Hire Badges for all employers/) do |named_person|
expect(page).to have_css('#shop_for_employer_sponsored_coverage', count: 2)
end
When(/(.*) click the first button of new hire badge/) do |named_person|
person = people[named_person]
expect(find_all(".alert-notice").first.text).to match person[:legal_name]
find_all('#shop_for_employer_sponsored_coverage').first.click
end
Then(/(.*) should see the 1st ER name/) do |named_person|
person = people[named_person]
expect(page).to have_content(person[:legal_name])
end
Then(/(.*) should see New Hire Badges for 2st ER/) do |named_person|
person = people[named_person]
expect(page).to have_content(person[:mlegal_name])
end
When(/(.*) click the button of new hire badge for 2st ER/) do |named_person|
#py =Person.last.active_employee_roles.last.census_employee.renewal_benefit_group_assignment.benefit_group.plan_year
#py.publish!
find_all('#shop_for_employer_sponsored_coverage').last.click
end
Then(/(.*) should see the 2st ER name/) do |named_person|
person = people[named_person]
expect(page).to have_content(person[:mlegal_name])
end
Then(/(.*) should see \"open enrollment not yet started\" error message/) do |named_person|
person = people[named_person]
employer_profile = EmployerProfile.find_by_fein(person[:fein])
find('.alert', text: "Open enrollment for your employer-sponsored benefits not yet started. Please return on #{employer_profile.renewing_plan_year.open_enrollment_start_on.strftime("%m/%d/%Y")} to enroll for coverage.")
visit '/families/home'
end
Then(/(.*) should get plan year start date as coverage effective date/) do |named_person|
person = people[named_person]
employer_profile = EmployerProfile.find_by_fein(person[:fein])
find('.coverage_effective_date', text: employer_profile.renewing_plan_year.start_on.strftime("%m/%d/%Y"))
end
Then(/(.*) should get qle effective date as coverage effective date/) do |named_person|
person = people[named_person]
effective_on = Person.where(:first_name=> person[:first_name]).first.primary_family.current_sep.effective_on
find('.coverage_effective_date', text: effective_on.strftime("%m/%d/%Y"))
end
When(/(.+) should see coverage summary page with renewing plan year start date as effective date/) do |named_person|
step "#{named_person} should get plan year start date as coverage effective date"
find('.interaction-click-control-confirm').click
end
Then(/(.+) should see coverage summary page with qle effective date/) do |named_person|
step "#{named_person} should get qle effective date as coverage effective date"
find('.interaction-click-control-confirm').click
end
Then(/(.*) should see the receipt page with qle effective date as effective date/) do |named_person|
expect(page).to have_content('Enrollment Submitted')
step "#{named_person} should get qle effective date as coverage effective date"
if page.has_link?('CONTINUE')
click_link "CONTINUE"
else
click_link "GO TO MY ACCOUNT"
end
end
Then(/(.*) should see the receipt page with renewing plan year start date as effective date/) do |named_person|
expect(page).to have_content('Enrollment Submitted')
step "#{named_person} should get plan year start date as coverage effective date"
if page.has_link?('CONTINUE')
click_link "CONTINUE"
else
click_link "GO TO MY ACCOUNT"
end
end
When(/Employee click the "(.*?)" in qle carousel/) do |qle_event|
click_link "#{qle_event}"
end
When(/Employee select a past qle date/) do
expect(page).to have_content "Married"
screenshot("past_qle_date")
fill_in "qle_date", :with => (TimeKeeper.date_of_record - 5.days).strftime("%m/%d/%Y")
within '#qle-date-chose' do
click_link "CONTINUE"
end
end
When(/Employee select a qle date based on expired plan year/) do
screenshot("past_qle_date")
fill_in "qle_date", :with => (TimeKeeper.date_of_record - 30.days).strftime("%m/%d/%Y")
within '#qle-date-chose' do
click_link "CONTINUE"
end
end
Then(/Employee should see confirmation and clicks continue/) do
expect(page).to have_content "Based on the information you entered, you may be eligible to enroll now but there is limited time"
screenshot("valid_qle")
click_button "Continue"
end
Then(/Employee should see family members page and clicks continue/) do
expect(page).to have_content "Household Info: Family Members"
within '#dependent_buttons' do
click_link "Continue"
end
end
| 50.164875 | 221 | 0.639183 |
f860ec18178c6f20fe6637e221c57b35aca4ad6e | 21,593 | #
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
require File.expand_path('../../../helper', __FILE__)
class Redfish::Tasks::Glassfish::TestApplication < Redfish::Tasks::Glassfish::BaseTaskTest
def setup
super
@location = @war_location = @deployment_plan = nil
end
def test_interpret_create
data = {'applications' => resource_parameters_as_tree}
executor = Redfish::Executor.new
context = create_simple_context(executor)
setup_interpreter_expects(executor, context, '')
executor.expects(:exec).with(equals(context),
equals('deploydir'),
equals(['--name', 'MyApplication', '--enabled=true', '--force=true', '--type', 'war', '--contextroot=/myapp', '--generatermistubs=true', '--availabilityenabled=true', '--lbenabled=true', '--keepstate=true', '--verify=true', '--precompilejsp=true', '--asyncreplication=true', '--deploymentplan', "#{self.temp_dir}/myapp-plan.jar", '--deploymentorder', '100', '--property', 'java-web-start-enabled=false', "#{self.temp_dir}/myapp"]),
equals({})).
returns("Command deploy executed successfully.\n")
executor.expects(:exec).with(equals(context),
equals('get'),
equals(['applications.application.MyApplication.property.org.glassfish.*']),
equals(:terse => true, :echo => false)).
returns('')
executor.expects(:exec).with(equals(context),
equals('get'),
equals(['applications.application.MyApplication.module.*']),
equals(:terse => true, :echo => false)).
returns('')
perform_interpret(context, data, true, :create, :additional_unchanged_task_count => 1)
end
def test_interpret_create_when_exists
data = {'applications' => resource_parameters_as_tree}
executor = Redfish::Executor.new
context = create_simple_context(executor)
setup_interpreter_expects(executor, context, to_properties_content)
perform_interpret(context, data, false, :create, :additional_unchanged_task_count => expected_local_properties.size)
end
def test_to_s
executor = Redfish::Executor.new
t = new_task(executor)
t.options = resource_parameters
assert_equal t.to_s, 'application[MyApplication]'
end
def test_create_element_where_cache_not_present_and_element_not_present
executor = Redfish::Executor.new
t = new_task(executor)
t.options = resource_parameters
executor.expects(:exec).with(equals(t.context), equals('list-applications'), equals(%w()), equals(:terse => true, :echo => false)).
returns('')
executor.expects(:exec).with(equals(t.context),
equals('deploydir'),
equals(['--name', 'MyApplication', '--enabled=true', '--force=true', '--type', 'war', '--contextroot=/myapp', '--generatermistubs=true', '--availabilityenabled=true', '--lbenabled=true', '--keepstate=true', '--verify=true', '--precompilejsp=true', '--asyncreplication=true', '--deploymentplan', "#{self.temp_dir}/myapp-plan.jar", '--deploymentorder', '100', '--property', 'java-web-start-enabled=false', "#{self.temp_dir}/myapp"]),
equals({})).
returns("Command deploy executed successfully.\n")
executor.expects(:exec).with(equals(t.context), equals('get'),
equals(["#{property_prefix}deployment-order"]),
equals(:terse => true, :echo => false)).
returns("#{property_prefix}deployment-order=100\n")
t.perform_action(:create)
ensure_task_updated_by_last_action(t)
end
def test_create_element_where_cache_not_present_and_element_present
executor = Redfish::Executor.new
t = new_task(executor)
t.options = resource_parameters
executor.expects(:exec).with(equals(t.context), equals('list-applications'), equals(%w()), equals(:terse => true, :echo => false)).
returns("MyApplication <web>\n")
executor.expects(:exec).with(equals(t.context), equals('get'), equals(%W(#{property_prefix}property.*)), equals(:terse => true, :echo => false)).
returns('')
expected_local_properties.each_pair do |k, v|
executor.expects(:exec).with(equals(t.context),
equals('get'),
equals(["#{property_prefix}#{k}"]),
equals(:terse => true, :echo => false)).
returns("#{property_prefix}#{k}=#{v}\n")
end
t.perform_action(:create)
ensure_task_not_updated_by_last_action(t)
end
def test_create_element_where_cache_not_present_and_element_present_but_modified
executor = Redfish::Executor.new
t = new_task(executor)
t.options = resource_parameters
executor.expects(:exec).with(equals(t.context), equals('list-applications'), equals(%w()), equals(:terse => true, :echo => false)).
returns("MyApplication <web>\n")
# Return a property that should be deleted
executor.expects(:exec).with(equals(t.context), equals('get'), equals(%W(#{property_prefix}property.*)), equals(:terse => true, :echo => false)).
returns("#{property_prefix}property.Blah=Y\n")
values = expected_local_properties
values['deployment-order'] = '101'
values['enabled'] = 'false'
values.each_pair do |k, v|
executor.expects(:exec).with(equals(t.context),
equals('get'),
equals(["#{property_prefix}#{k}"]),
equals(:terse => true, :echo => false)).
returns("#{property_prefix}#{k}=#{v}\n")
end
executor.expects(:exec).with(equals(t.context),
equals('set'),
equals(["#{property_prefix}enabled=true"]),
equals(:terse => true, :echo => false))
executor.expects(:exec).with(equals(t.context),
equals('set'),
equals(["#{property_prefix}deployment-order=100"]),
equals(:terse => true, :echo => false))
executor.expects(:exec).with(equals(t.context),
equals('get'),
equals(["#{property_prefix}property.Blah"]),
equals(:terse => true, :echo => false)).
returns("#{property_prefix}property.Blah=X\n")
# This is the set to remove property that should not exist
executor.expects(:exec).with(equals(t.context),
equals('set'),
equals(["#{property_prefix}property.Blah="]),
equals(:terse => true, :echo => false)).
returns('')
t.perform_action(:create)
ensure_task_updated_by_last_action(t)
end
def test_create_element_where_cache_present_and_element_not_present
executor = Redfish::Executor.new
t = new_task(executor)
t.context.cache_properties({})
t.options = resource_parameters
executor.expects(:exec).with(equals(t.context),
equals('deploydir'),
equals(['--name', 'MyApplication', '--enabled=true', '--force=true', '--type', 'war', '--contextroot=/myapp', '--generatermistubs=true', '--availabilityenabled=true', '--lbenabled=true', '--keepstate=true', '--verify=true', '--precompilejsp=true', '--asyncreplication=true', '--deploymentplan', "#{self.temp_dir}/myapp-plan.jar", '--deploymentorder', '100', '--property', 'java-web-start-enabled=false', "#{self.temp_dir}/myapp"]),
equals({})).
returns("Command deploy executed successfully.\n")
executor.expects(:exec).with(equals(t.context),
equals('get'),
equals(['applications.application.MyApplication.property.org.glassfish.*']),
equals(:terse => true, :echo => false)).
returns("applications.application.MyApplication.property.org.glassfish.ejb.container.application_unique_id=96073498887454720\n" +
"applications.application.MyApplication.property.org.glassfish.persistence.app_name_property=MyApplication\n")
executor.expects(:exec).with(equals(t.context),
equals('get'),
equals(['applications.application.MyApplication.module.*']),
equals(:terse => true, :echo => false)).
returns("applications.application.MyApplication.module.A=a\n" +
"applications.application.MyApplication.module.B=b\n" +
"applications.application.MyApplication.module.C=c\n")
t.perform_action(:create)
ensure_task_updated_by_last_action(t)
ensure_expected_cache_values(t)
assert_equal t.context.property_cache['applications.application.MyApplication.module.A'], 'a'
assert_equal t.context.property_cache['applications.application.MyApplication.module.B'], 'b'
assert_equal t.context.property_cache['applications.application.MyApplication.module.C'], 'c'
assert_equal t.context.property_cache['applications.application.MyApplication.module.X'], ''
assert_equal t.context.property_cache['applications.application.MyApplication.property.org.glassfish.ejb.container.application_unique_id'], '96073498887454720'
assert_equal t.context.property_cache['applications.application.MyApplication.property.org.glassfish.persistence.app_name_property'], 'MyApplication'
end
def test_create_element_where_cache_present_and_element_not_present_for_war
executor = Redfish::Executor.new
t = new_task(executor)
t.context.cache_properties({})
t.options = resource_parameters.merge('location' => self.location_as_war)
executor.expects(:exec).with(equals(t.context),
equals('deploy'),
equals(['--name', 'MyApplication', '--enabled=true', '--force=true', '--type', 'war', '--contextroot=/myapp', '--generatermistubs=true', '--availabilityenabled=true', '--lbenabled=true', '--keepstate=true', '--verify=true', '--precompilejsp=true', '--asyncreplication=true', '--deploymentplan', "#{self.temp_dir}/myapp-plan.jar", '--deploymentorder', '100', '--property', 'java-web-start-enabled=false', self.location_as_war]),
equals({})).
returns("Command deploy executed successfully.\n")
executor.expects(:exec).with(equals(t.context),
equals('get'),
equals(['applications.application.MyApplication.property.org.glassfish.*']),
equals(:terse => true, :echo => false)).
returns('')
executor.expects(:exec).with(equals(t.context),
equals('get'),
equals(['applications.application.MyApplication.module.*']),
equals(:terse => true, :echo => false)).
returns('')
t.perform_action(:create)
ensure_task_updated_by_last_action(t)
ensure_expected_cache_values(t,
"#{property_prefix}directory-deployed" => 'false',
"#{property_prefix}location" => "${com.sun.aas.instanceRootURI}/applications/MyApplication/",
"#{property_prefix}property.appLocation" => "${com.sun.aas.instanceRootURI}/applications/__internal/MyApplication/myapp.war")
end
def test_create_element_where_cache_present_and_element_present_but_modified
cache_values = expected_properties
executor = Redfish::Executor.new
t = new_task(executor)
cache_values["#{property_prefix}enabled"] = 'false'
cache_values["#{property_prefix}deployment-order"] = '101'
# This property should be removed
cache_values["#{property_prefix}property.Blah"] = 'X'
t.context.cache_properties(cache_values)
t.options = resource_parameters
executor.expects(:exec).with(equals(t.context),
equals('set'),
equals(["#{property_prefix}property.Blah="]),
equals(:terse => true, :echo => false))
executor.expects(:exec).with(equals(t.context),
equals('set'),
equals(["#{property_prefix}deployment-order=100"]),
equals(:terse => true, :echo => false))
executor.expects(:exec).with(equals(t.context),
equals('set'),
equals(["#{property_prefix}enabled=true"]),
equals(:terse => true, :echo => false))
t.perform_action(:create)
ensure_task_updated_by_last_action(t)
ensure_expected_cache_values(t)
end
def test_create_element_where_cache_present_and_element_present
t = new_task
t.context.cache_properties(expected_properties)
t.options = resource_parameters
t.perform_action(:create)
ensure_task_not_updated_by_last_action(t)
ensure_expected_cache_values(t)
end
def test_delete_element_where_cache_not_present_and_element_not_present
executor = Redfish::Executor.new
t = new_task(executor)
t.options = {'name' => 'MyApplication'}
executor.expects(:exec).with(equals(t.context),
equals('list-applications'),
equals([]),
equals({:terse => true, :echo => false})).
returns('')
t.perform_action(:destroy)
ensure_task_not_updated_by_last_action(t)
end
def test_delete_element_where_cache_not_present_and_element_present
executor = Redfish::Executor.new
t = new_task(executor)
t.options = {'name' => 'MyApplication'}
executor.expects(:exec).with(equals(t.context),
equals('list-applications'),
equals([]),
equals({:terse => true, :echo => false})).
returns("MyApplication <web>\n")
executor.expects(:exec).with(equals(t.context),
equals('undeploy'),
equals(['--cascade=false', 'MyApplication']),
equals({})).
returns('')
t.perform_action(:destroy)
ensure_task_updated_by_last_action(t)
end
def test_delete_element_where_cache_present_and_element_not_present
t = new_task
t.context.cache_properties({})
t.options = {'name' => 'MyApplication'}
t.perform_action(:destroy)
ensure_task_not_updated_by_last_action(t)
ensure_properties_not_present(t)
end
def test_delete_element_where_cache_present_and_element_present
executor = Redfish::Executor.new
t = new_task(executor)
t.context.cache_properties(expected_properties)
t.options = {'name' => 'MyApplication'}
executor.expects(:exec).with(equals(t.context),
equals('undeploy'),
equals(['--cascade=false', 'MyApplication']),
equals({})).
returns('')
t.perform_action(:destroy)
ensure_task_updated_by_last_action(t)
ensure_properties_not_present(t)
end
def test_interpret_create_and_delete
data = {'applications' => resource_parameters_as_tree(:managed => true)}
executor = Redfish::Executor.new
context = create_simple_context(executor)
existing = %w(Element1 Element2-2.5.1)
setup_interpreter_expects_with_fake_elements(executor, context, existing, raw_property_prefix, %w(object-type))
executor.expects(:exec).with(equals(context),
equals('deploydir'),
equals(['--name', 'MyApplication', '--enabled=true', '--force=true', '--type', 'war', '--contextroot=/myapp', '--generatermistubs=true', '--availabilityenabled=true', '--lbenabled=true', '--keepstate=true', '--verify=true', '--precompilejsp=true', '--asyncreplication=true', '--deploymentplan', "#{self.temp_dir}/myapp-plan.jar", '--deploymentorder', '100', '--property', 'java-web-start-enabled=false', "#{self.temp_dir}/myapp"]),
equals({})).
returns("Command deploy executed successfully.\n")
executor.expects(:exec).with(equals(context),
equals('get'),
equals(['applications.application.MyApplication.property.org.glassfish.*']),
equals(:terse => true, :echo => false)).
returns('')
executor.expects(:exec).with(equals(context),
equals('get'),
equals(['applications.application.MyApplication.module.*']),
equals(:terse => true, :echo => false)).
returns('')
existing.each do |element|
executor.expects(:exec).with(equals(context),
equals('undeploy'),
equals(['--cascade=false', element]),
equals({})).
returns('')
end
perform_interpret(context, data, true, :create, :additional_task_count => 1 + existing.size, :additional_unchanged_task_count => 1)
end
def test_cleaner_deletes_unexpected_element
executor = Redfish::Executor.new
t = new_cleaner_task(executor)
existing = %w(Element1 Element2.3-4.23 Element3)
create_fake_elements(t.context, existing, raw_property_prefix, %w(object-type))
t.expected = existing[1, existing.size]
executor.expects(:exec).with(equals(t.context),
equals('undeploy'),
equals(['--cascade=false', existing.first]),
equals({})).
returns('')
t.perform_action(:clean)
ensure_task_updated_by_last_action(t)
ensure_properties_not_present(t, "#{raw_property_prefix}#{existing.first}")
end
def test_cleaner_not_updated_if_no_clean_actions
executor = Redfish::Executor.new
t = new_cleaner_task(executor)
existing = %w(Element1 Element2 Element3)
create_fake_elements(t.context, existing)
t.expected = existing
t.perform_action(:clean)
ensure_task_not_updated_by_last_action(t)
end
protected
def property_prefix
"#{raw_property_prefix}MyApplication."
end
def location_as_war
unless @war_location
@war_location = "#{self.temp_dir}/myapp.war"
FileUtils.touch "#{self.temp_dir}/file.txt"
`jar -cf #{@war_location} #{self.temp_dir}/file.txt`
end
@war_location
end
def location_as_dir
unless @location
@location = "#{self.temp_dir}/myapp"
FileUtils.mkdir_p @location
File.open("#{@location}/index.txt", 'w') { |f| f << 'Hi' }
end
@location
end
def deployment_plan
unless @deployment_plan
@deployment_plan = "#{self.temp_dir}/myapp-plan.jar"
File.open(@deployment_plan, 'w') { |f| f << '' }
end
@deployment_plan
end
# Properties in GlassFish properties directory
def expected_local_properties
{
'enabled' => 'true',
'async-replication' => 'true',
'availability-enabled' => 'true',
'directory-deployed' => 'true',
'context-root' => '/myapp',
'location' => "file:#{self.location_as_dir}/",
'property.defaultAppName' => 'myapp',
'property.archiveType' => 'war',
'property.appLocation' => "file:#{self.location_as_dir}/",
'property.java-web-start-enabled' => 'false',
'deployment-order' => '100'
}
end
# Resource parameters
def resource_parameters
{
'name' => 'MyApplication',
'location' => self.location_as_dir,
'deployment_plan' => self.deployment_plan,
'context_root' => '/myapp',
'enabled' => 'true',
'type' => 'war',
'generate_rmi_stubs' => 'true',
'availability_enabled' => 'true',
'lb_enabled' => 'true',
'keep_state' => 'true',
'verify' => 'true',
'precompile_jsp' => 'true',
'async_replication' => 'true',
'properties' => {'java-web-start-enabled' => 'false'},
'deployment_order' => 100
}
end
def reference_properties
name = self.resource_name
{
"servers.server.server.application-ref.#{name}.enabled" => 'true',
"servers.server.server.application-ref.#{name}.lb-enabled" => 'true',
"servers.server.server.application-ref.#{name}.virtual-servers" => 'server',
"servers.server.server.application-ref.#{name}.disable-timeout-in-minutes" => '30',
"servers.server.server.application-ref.#{name}.ref" => name
}
end
end
| 42.091618 | 464 | 0.60339 |
ff27efd9520daa2a01884cb508e3d32489b0431d | 1,669 | class DefectPresenter < SimpleDelegator
delegate :contractor_name, to: :scheme
delegate :contractor_email_address, to: :scheme
delegate :name, to: :priority, prefix: :priority
def reporting_officer
'Hackney New Build team'
end
def address
communal? ? communal_area.location : property.address
end
def defect_type
property.present? ? 'Property' : 'Communal'
end
def created_at
super.to_date.to_s
end
def accepted_on
acceptance_event = activities.find_by(key: 'defect.accepted')
return I18n.t('page_content.defect.show.not_accepted_yet') unless acceptance_event
acceptance_event.created_at.to_s
end
def target_completion_date
super.to_s
end
def actual_completion_date
super.to_s
end
def category
return 'Plumbing' if Defect::PLUMBING_TRADES.include?(trade)
return 'Electrical/Mechanical' if Defect::ELECTRICAL_TRADES.include?(trade)
return 'Carpentry/Doors' if Defect::CARPENTRY_TRADES.include?(trade)
return 'Cosmetic' if Defect::COSMETIC_TRADES.include?(trade)
trade
end
def flagged_tag
'flagged' if flagged?
end
# rubocop:disable Metrics/AbcSize
def to_row
[
reference_number,
created_at.to_s,
added_at.to_s,
title,
defect_type,
status,
trade,
category,
priority.name,
priority.days,
target_completion_date,
actual_completion_date,
scheme.estate.name,
scheme.name,
property&.address,
communal_area&.name,
communal_area&.location,
description,
access_information,
flagged_tag,
]
end
# rubocop:enable Metrics/AbcSize
end
| 21.960526 | 86 | 0.698622 |
e2a401d0c87ef6441c2ca0bb1bbe6dc4696b8a11 | 923 | module RubyLint
module Template
##
# Class used for storing variables for an ERB template without polluting
# the namespace of the code that uses the template.
#
class Scope
##
# @param [Hash] variables
#
def initialize(variables = {})
variables.each do |name, value|
instance_variable_set("@#{name}", value)
end
end
##
# Returns `true` if the method's definition should return an instance of
# the container.
#
# @param [Symbol] type
# @param [Symbol] name
#
def return_instance?(type, name)
return (type == :method && name == :new) ||
(type == :instance_method && name == :initialize)
end
##
# @return [Binding]
#
def get_binding
return binding # #binding() is a private method.
end
end # Scope
end # Template
end # RubyLint
| 24.289474 | 78 | 0.561213 |
18881dbbd159013d5bd4f574b3199b9b088c07c3 | 1,635 | module Codebreaker
class Game
HINTS = 3
CODE_SIZE = 4
ATTEMPTS = 5
RANGE_NUMBER = 1..6
attr_accessor :secret_code, :user_code
def initialize
@secret_code = secret_code
@user_code = user_code
@hint = HINTS
end
def new_game
start
input_user_code
attempts
win?
end
def start
@secret_code = Array.new(CODE_SIZE){rand(RANGE_NUMBER)}
end
def input_user_code
@user_code = []
puts "Enter your code numbers(only 1 to 6)"
CODE_SIZE.times do
user_code << gets.chomp.to_i
end
user_code
end
def count_plus
plus = []
CODE_SIZE.times do |i|
if user_code[i] == secret_code[i]
plus << "+"
end
end
plus
end
def count_minus
minus = []
CODE_SIZE.times do |i|
if user_code.include?(secret_code[i]) && user_code[i] != secret_code[i]
minus << "-"
end
end
minus
end
def count_plus_and_minus
count = []
count << count_plus.concat(count_minus).to_s
puts count
end
def win?
if (@secret_code - @user_code).empty?
puts "Congratulation!You win"
end
end
def attempts
ATTEMPTS.times do |i|
unless @secret_code == @user_code
count_plus_and_minus
input_user_code
end
end
end
def hint
@hint -= 1
end
def take_hint!
random_hint = rand(CODE_SIZE)
hint = secret_code[random_hint].to_s
hint
end
end
end
| 18.166667 | 79 | 0.542508 |
38ba06c08420c05bc2928c5b5b2e120f7b0bde04 | 2,096 | require 'spec_helper'
require 'ddtrace/contrib/sucker_punch/integration'
RSpec.describe Datadog::Contrib::SuckerPunch::Integration do
extend ConfigurationHelpers
let(:integration) { described_class.new(:sucker_punch) }
describe '.version' do
subject(:version) { described_class.version }
context 'when the "sucker_punch" gem is loaded' do
include_context 'loaded gems', sucker_punch: described_class::MINIMUM_VERSION
it { is_expected.to be_a_kind_of(Gem::Version) }
end
context 'when "sucker_punch" gem is not loaded' do
include_context 'loaded gems', sucker_punch: nil
it { is_expected.to be nil }
end
end
describe '.loaded?' do
subject(:loaded?) { described_class.loaded? }
context 'when SuckerPunch is defined' do
before { stub_const('SuckerPunch', Class.new) }
it { is_expected.to be true }
end
context 'when SuckerPunch is not defined' do
before { hide_const('SuckerPunch') }
it { is_expected.to be false }
end
end
describe '.compatible?' do
subject(:compatible?) { described_class.compatible? }
context 'when "sucker_punch" gem is loaded with a version' do
context 'that is less than the minimum' do
include_context 'loaded gems', sucker_punch: decrement_gem_version(described_class::MINIMUM_VERSION)
it { is_expected.to be false }
end
context 'that meets the minimum version' do
include_context 'loaded gems', sucker_punch: described_class::MINIMUM_VERSION
it { is_expected.to be true }
end
end
context 'when gem is not loaded' do
include_context 'loaded gems', sucker_punch: nil
it { is_expected.to be false }
end
end
describe '#default_configuration' do
subject(:default_configuration) { integration.default_configuration }
it { is_expected.to be_a_kind_of(Datadog::Contrib::SuckerPunch::Configuration::Settings) }
end
describe '#patcher' do
subject(:patcher) { integration.patcher }
it { is_expected.to be Datadog::Contrib::SuckerPunch::Patcher }
end
end
| 30.376812 | 108 | 0.701813 |
265fa499eb2bb5528f0682ba17e9e56b90bdbd25 | 49,727 | require 'test/unit'
require 'pp'
require_relative 'envutil'
$m0 = Module.nesting
class TestModule < Test::Unit::TestCase
def _wrap_assertion
yield
end
def assert_method_defined?(klass, mid, message="")
message = build_message(message, "#{klass}\##{mid} expected to be defined.")
_wrap_assertion do
klass.method_defined?(mid) or
raise Test::Unit::AssertionFailedError, message, caller(3)
end
end
def assert_method_not_defined?(klass, mid, message="")
message = build_message(message, "#{klass}\##{mid} expected to not be defined.")
_wrap_assertion do
klass.method_defined?(mid) and
raise Test::Unit::AssertionFailedError, message, caller(3)
end
end
def setup
@verbose = $VERBOSE
$VERBOSE = nil
end
def teardown
$VERBOSE = @verbose
end
def test_LT_0
assert_equal true, String < Object
assert_equal false, Object < String
assert_nil String < Array
assert_equal true, Array < Enumerable
assert_equal false, Enumerable < Array
assert_nil Proc < Comparable
assert_nil Comparable < Proc
end
def test_GT_0
assert_equal false, String > Object
assert_equal true, Object > String
assert_nil String > Array
assert_equal false, Array > Enumerable
assert_equal true, Enumerable > Array
assert_nil Comparable > Proc
assert_nil Proc > Comparable
end
def test_CMP_0
assert_equal(-1, (String <=> Object))
assert_equal 1, (Object <=> String)
assert_nil(Array <=> String)
end
ExpectedException = NoMethodError
# Support stuff
module Mixin
MIXIN = 1
def mixin
end
end
module User
USER = 2
include Mixin
def user
end
end
module Other
def other
end
end
class AClass
def AClass.cm1
"cm1"
end
def AClass.cm2
cm1 + "cm2" + cm3
end
def AClass.cm3
"cm3"
end
private_class_method :cm1, "cm3"
def aClass
:aClass
end
def aClass1
:aClass1
end
def aClass2
:aClass2
end
private :aClass1
protected :aClass2
end
class BClass < AClass
def bClass1
:bClass1
end
private
def bClass2
:bClass2
end
protected
def bClass3
:bClass3
end
end
class CClass < BClass
def self.cClass
end
end
MyClass = AClass.clone
class MyClass
public_class_method :cm1
end
# -----------------------------------------------------------
def test_CMP # '<=>'
assert_equal( 0, Mixin <=> Mixin)
assert_equal(-1, User <=> Mixin)
assert_equal( 1, Mixin <=> User)
assert_equal( 0, Object <=> Object)
assert_equal(-1, String <=> Object)
assert_equal( 1, Object <=> String)
end
def test_GE # '>='
assert_operator(Mixin, :>=, User)
assert_operator(Mixin, :>=, Mixin)
assert_not_operator(User, :>=, Mixin)
assert_operator(Object, :>=, String)
assert_operator(String, :>=, String)
assert_not_operator(String, :>=, Object)
end
def test_GT # '>'
assert_operator(Mixin, :>, User)
assert_not_operator(Mixin, :>, Mixin)
assert_not_operator(User, :>, Mixin)
assert_operator(Object, :>, String)
assert_not_operator(String, :>, String)
assert_not_operator(String, :>, Object)
end
def test_LE # '<='
assert_operator(User, :<=, Mixin)
assert_operator(Mixin, :<=, Mixin)
assert_not_operator(Mixin, :<=, User)
assert_operator(String, :<=, Object)
assert_operator(String, :<=, String)
assert_not_operator(Object, :<=, String)
end
def test_LT # '<'
assert_operator(User, :<, Mixin)
assert_not_operator(Mixin, :<, Mixin)
assert_not_operator(Mixin, :<, User)
assert_operator(String, :<, Object)
assert_not_operator(String, :<, String)
assert_not_operator(Object, :<, String)
end
def test_VERY_EQUAL # '==='
assert_operator(Object, :===, self)
assert_operator(Test::Unit::TestCase, :===, self)
assert_operator(TestModule, :===, self)
assert_not_operator(String, :===, self)
end
def test_ancestors
assert_equal([User, Mixin], User.ancestors)
assert_equal([Mixin], Mixin.ancestors)
ancestors = Object.ancestors
mixins = ancestors - [Object, Kernel, BasicObject]
mixins << JSON::Ext::Generator::GeneratorMethods::String if defined?(JSON::Ext::Generator::GeneratorMethods::String)
assert_equal([Object, Kernel, BasicObject], ancestors - mixins)
assert_equal([String, Comparable, Object, Kernel, BasicObject], String.ancestors - mixins)
end
CLASS_EVAL = 2
@@class_eval = 'b'
def test_class_eval
Other.class_eval("CLASS_EVAL = 1")
assert_equal(1, Other::CLASS_EVAL)
assert_include(Other.constants, :CLASS_EVAL)
assert_equal(2, Other.class_eval { CLASS_EVAL })
Other.class_eval("@@class_eval = 'a'")
assert_equal('a', Other.class_variable_get(:@@class_eval))
assert_equal('b', Other.class_eval { @@class_eval })
Other.class_eval do
module_function
def class_eval_test
"foo"
end
end
assert_equal("foo", Other.class_eval_test)
assert_equal([Other], Other.class_eval { |*args| args })
end
def test_const_defined?
assert_operator(Math, :const_defined?, :PI)
assert_operator(Math, :const_defined?, "PI")
assert_not_operator(Math, :const_defined?, :IP)
assert_not_operator(Math, :const_defined?, "IP")
end
def each_bad_constants(m, &b)
[
"#<Class:0x7b8b718b>",
":Object",
"",
":",
["String::", "[Bug #7573]"],
"\u3042",
"Name?",
].each do |name, msg|
expected = "wrong constant name %s" % quote(name)
msg = "#{msg}#{': ' if msg}wrong constant name #{name.dump}"
assert_raise_with_message(NameError, expected, "#{msg} to #{m}") do
yield name
end
end
end
def test_bad_constants_get
each_bad_constants("get") {|name|
Object.const_get name
}
end
def test_bad_constants_defined
each_bad_constants("defined?") {|name|
Object.const_defined? name
}
end
def test_leading_colons
assert_equal Object, AClass.const_get('::Object')
end
def test_const_get
assert_equal(Math::PI, Math.const_get("PI"))
assert_equal(Math::PI, Math.const_get(:PI))
n = Object.new
def n.to_str; @count = defined?(@count) ? @count + 1 : 1; "PI"; end
def n.count; @count; end
assert_equal(Math::PI, Math.const_get(n))
assert_equal(1, n.count)
end
def test_nested_get
assert_equal Other, Object.const_get([self.class, Other].join('::'))
assert_equal User::USER, self.class.const_get([User, 'USER'].join('::'))
end
def test_nested_get_symbol
const = [self.class, Other].join('::').to_sym
assert_raise(NameError) {Object.const_get(const)}
const = [User, 'USER'].join('::').to_sym
assert_raise(NameError) {self.class.const_get(const)}
end
def test_nested_get_const_missing
classes = []
klass = Class.new {
define_singleton_method(:const_missing) { |name|
classes << name
klass
}
}
klass.const_get("Foo::Bar::Baz")
assert_equal [:Foo, :Bar, :Baz], classes
end
def test_nested_get_bad_class
assert_raise(TypeError) do
self.class.const_get([User, 'USER', 'Foo'].join('::'))
end
end
def test_nested_defined
assert_send([Object, :const_defined?, [self.class.name, 'Other'].join('::')])
assert_send([self.class, :const_defined?, 'User::USER'])
assert_not_send([self.class, :const_defined?, 'User::Foo'])
end
def test_nested_defined_symbol
const = [self.class, Other].join('::').to_sym
assert_raise(NameError) {Object.const_defined?(const)}
const = [User, 'USER'].join('::').to_sym
assert_raise(NameError) {self.class.const_defined?(const)}
end
def test_nested_defined_bad_class
assert_raise(TypeError) do
self.class.const_defined?('User::USER::Foo')
end
end
def test_const_set
assert_not_operator(Other, :const_defined?, :KOALA)
Other.const_set(:KOALA, 99)
assert_operator(Other, :const_defined?, :KOALA)
assert_equal(99, Other::KOALA)
Other.const_set("WOMBAT", "Hi")
assert_equal("Hi", Other::WOMBAT)
n = Object.new
def n.to_str; @count = defined?(@count) ? @count + 1 : 1; "HOGE"; end
def n.count; @count; end
def n.count=(v); @count=v; end
assert_not_operator(Other, :const_defined?, :HOGE)
Other.const_set(n, 999)
assert_equal(1, n.count)
n.count = 0
assert_equal(999, Other.const_get(n))
assert_equal(1, n.count)
n.count = 0
assert_equal(true, Other.const_defined?(n))
assert_equal(1, n.count)
end
def test_constants
assert_equal([:MIXIN], Mixin.constants)
assert_equal([:MIXIN, :USER], User.constants.sort)
end
def test_self_initialize_copy
bug9535 = '[ruby-dev:47989] [Bug #9535]'
m = Module.new do
def foo
:ok
end
initialize_copy(self)
end
assert_equal(:ok, Object.new.extend(m).foo, bug9535)
end
def test_initialize_copy_empty
bug9813 = '[ruby-dev:48182] [Bug #9813]'
m = Module.new do
def x
end
const_set(:X, 1)
@x = 2
end
assert_equal([:x], m.instance_methods)
assert_equal([:@x], m.instance_variables)
assert_equal([:X], m.constants)
m.module_eval do
initialize_copy(Module.new)
end
assert_empty(m.instance_methods, bug9813)
assert_empty(m.instance_variables, bug9813)
assert_empty(m.constants, bug9813)
end
def test_dup
bug6454 = '[ruby-core:45132]'
a = Module.new
Other.const_set :BUG6454, a
b = a.dup
Other.const_set :BUG6454_dup, b
assert_equal "TestModule::Other::BUG6454_dup", b.inspect, bug6454
end
def test_dup_anonymous
bug6454 = '[ruby-core:45132]'
a = Module.new
original = a.inspect
b = a.dup
assert_not_equal original, b.inspect, bug6454
end
def test_public_include
assert_nothing_raised('#8846') do
Module.new.include(Module.new { def foo; end }).instance_methods == [:foo]
end
end
def test_include_toplevel
assert_separately([], <<-EOS)
Mod = Module.new {def foo; :include_foo end}
TOPLEVEL_BINDING.eval('include Mod')
assert_equal(:include_foo, TOPLEVEL_BINDING.eval('foo'))
assert_equal([Object, Mod], Object.ancestors.slice(0, 2))
EOS
end
def test_included_modules
assert_equal([], Mixin.included_modules)
assert_equal([Mixin], User.included_modules)
mixins = Object.included_modules - [Kernel]
mixins << JSON::Ext::Generator::GeneratorMethods::String if defined?(JSON::Ext::Generator::GeneratorMethods::String)
assert_equal([Kernel], Object.included_modules - mixins)
assert_equal([Comparable, Kernel], String.included_modules - mixins)
end
def test_instance_methods
assert_equal([:user], User.instance_methods(false))
assert_equal([:user, :mixin].sort, User.instance_methods(true).sort)
assert_equal([:mixin], Mixin.instance_methods)
assert_equal([:mixin], Mixin.instance_methods(true))
assert_equal([:cClass], (class << CClass; self; end).instance_methods(false))
assert_equal([], (class << BClass; self; end).instance_methods(false))
assert_equal([:cm2], (class << AClass; self; end).instance_methods(false))
# Ruby 1.8 feature change:
# #instance_methods includes protected methods.
#assert_equal([:aClass], AClass.instance_methods(false))
assert_equal([:aClass, :aClass2], AClass.instance_methods(false).sort)
assert_equal([:aClass, :aClass2],
(AClass.instance_methods(true) - Object.instance_methods(true)).sort)
end
def test_method_defined?
assert_method_not_defined?(User, :wombat)
assert_method_defined?(User, :user)
assert_method_defined?(User, :mixin)
assert_method_not_defined?(User, :wombat)
assert_method_defined?(User, :user)
assert_method_defined?(User, :mixin)
end
def module_exec_aux
Proc.new do
def dynamically_added_method_3; end
end
end
def module_exec_aux_2(&block)
User.module_exec(&block)
end
def test_module_exec
User.module_exec do
def dynamically_added_method_1; end
end
assert_method_defined?(User, :dynamically_added_method_1)
block = Proc.new do
def dynamically_added_method_2; end
end
User.module_exec(&block)
assert_method_defined?(User, :dynamically_added_method_2)
User.module_exec(&module_exec_aux)
assert_method_defined?(User, :dynamically_added_method_3)
module_exec_aux_2 do
def dynamically_added_method_4; end
end
assert_method_defined?(User, :dynamically_added_method_4)
end
def test_module_eval
User.module_eval("MODULE_EVAL = 1")
assert_equal(1, User::MODULE_EVAL)
assert_include(User.constants, :MODULE_EVAL)
User.instance_eval("remove_const(:MODULE_EVAL)")
assert_not_include(User.constants, :MODULE_EVAL)
end
def test_name
assert_equal("Fixnum", Fixnum.name)
assert_equal("TestModule::Mixin", Mixin.name)
assert_equal("TestModule::User", User.name)
end
def test_classpath
m = Module.new
n = Module.new
m.const_set(:N, n)
assert_nil(m.name)
assert_nil(n.name)
assert_equal([:N], m.constants)
m.module_eval("module O end")
assert_equal([:N, :O], m.constants)
m.module_eval("class C; end")
assert_equal([:N, :O, :C], m.constants)
assert_nil(m::N.name)
assert_match(/\A#<Module:.*>::O\z/, m::O.name)
assert_match(/\A#<Module:.*>::C\z/, m::C.name)
self.class.const_set(:M, m)
prefix = self.class.name + "::M::"
assert_equal(prefix+"N", m.const_get(:N).name)
assert_equal(prefix+"O", m.const_get(:O).name)
assert_equal(prefix+"C", m.const_get(:C).name)
end
def test_private_class_method
assert_raise(ExpectedException) { AClass.cm1 }
assert_raise(ExpectedException) { AClass.cm3 }
assert_equal("cm1cm2cm3", AClass.cm2)
end
def test_private_instance_methods
assert_equal([:aClass1], AClass.private_instance_methods(false))
assert_equal([:bClass2], BClass.private_instance_methods(false))
assert_equal([:aClass1, :bClass2],
(BClass.private_instance_methods(true) -
Object.private_instance_methods(true)).sort)
end
def test_protected_instance_methods
assert_equal([:aClass2], AClass.protected_instance_methods)
assert_equal([:bClass3], BClass.protected_instance_methods(false))
assert_equal([:bClass3, :aClass2].sort,
(BClass.protected_instance_methods(true) -
Object.protected_instance_methods(true)).sort)
end
def test_public_class_method
assert_equal("cm1", MyClass.cm1)
assert_equal("cm1cm2cm3", MyClass.cm2)
assert_raise(ExpectedException) { eval "MyClass.cm3" }
end
def test_public_instance_methods
assert_equal([:aClass], AClass.public_instance_methods(false))
assert_equal([:bClass1], BClass.public_instance_methods(false))
end
def test_s_constants
c1 = Module.constants
Object.module_eval "WALTER = 99"
c2 = Module.constants
assert_equal([:WALTER], c2 - c1)
assert_equal([], Module.constants(true))
assert_equal([], Module.constants(false))
src = <<-INPUT
ary = Module.constants
module M
WALTER = 99
end
class Module
include M
end
p Module.constants - ary, Module.constants(true), Module.constants(false)
INPUT
assert_in_out_err([], src, %w([:M] [:WALTER] []), [])
klass = Class.new do
const_set(:X, 123)
end
assert_equal(false, klass.class_eval { Module.constants }.include?(:X))
end
module M1
$m1 = Module.nesting
module M2
$m2 = Module.nesting
end
end
def test_s_nesting
assert_equal([], $m0)
assert_equal([TestModule::M1, TestModule], $m1)
assert_equal([TestModule::M1::M2,
TestModule::M1, TestModule], $m2)
end
def test_s_new
m = Module.new
assert_instance_of(Module, m)
end
def test_freeze
m = Module.new
m.freeze
assert_raise(RuntimeError) do
m.module_eval do
def foo; end
end
end
end
def test_attr_obsoleted_flag
c = Class.new
c.class_eval do
def initialize
@foo = :foo
@bar = :bar
end
attr :foo, true
attr :bar, false
end
o = c.new
assert_equal(true, o.respond_to?(:foo))
assert_equal(true, o.respond_to?(:foo=))
assert_equal(true, o.respond_to?(:bar))
assert_equal(false, o.respond_to?(:bar=))
end
def test_const_get_evaled
c1 = Class.new
c2 = Class.new(c1)
eval("c1::Foo = :foo")
assert_equal(:foo, c1::Foo)
assert_equal(:foo, c2::Foo)
assert_equal(:foo, c2.const_get(:Foo))
assert_raise(NameError) { c2.const_get(:Foo, false) }
eval("c1::Foo = :foo")
assert_raise(NameError) { c1::Bar }
assert_raise(NameError) { c2::Bar }
assert_raise(NameError) { c2.const_get(:Bar) }
assert_raise(NameError) { c2.const_get(:Bar, false) }
assert_raise(NameError) { c2.const_get("Bar", false) }
assert_raise(NameError) { c2.const_get("BaR11", false) }
assert_raise(NameError) { Object.const_get("BaR11", false) }
c1.instance_eval do
def const_missing(x)
x
end
end
assert_equal(:Bar, c1::Bar)
assert_equal(:Bar, c2::Bar)
assert_equal(:Bar, c2.const_get(:Bar))
assert_equal(:Bar, c2.const_get(:Bar, false))
assert_equal(:Bar, c2.const_get("Bar"))
assert_equal(:Bar, c2.const_get("Bar", false))
v = c2.const_get("Bar11", false)
assert_equal("Bar11".to_sym, v)
assert_raise(NameError) { c1.const_get(:foo) }
end
def test_const_set_invalid_name
c1 = Class.new
assert_raise(NameError) { c1.const_set(:foo, :foo) }
assert_raise(NameError) { c1.const_set("bar", :foo) }
assert_raise(TypeError) { c1.const_set(1, :foo) }
end
def test_const_get_invalid_name
c1 = Class.new
assert_raise(NameError) { c1.const_get(:foo) }
bug5084 = '[ruby-dev:44200]'
assert_raise(TypeError, bug5084) { c1.const_get(1) }
bug7574 = '[ruby-dev:46749]'
assert_raise_with_message(NameError, "wrong constant name \"String\\u0000\"", bug7574) {
Object.const_get("String\0")
}
end
def test_const_defined_invalid_name
c1 = Class.new
assert_raise(NameError) { c1.const_defined?(:foo) }
bug5084 = '[ruby-dev:44200]'
assert_raise(TypeError, bug5084) { c1.const_defined?(1) }
bug7574 = '[ruby-dev:46749]'
assert_raise_with_message(NameError, "wrong constant name \"String\\u0000\"", bug7574) {
Object.const_defined?("String\0")
}
end
def test_const_get_no_inherited
bug3422 = '[ruby-core:30719]'
assert_in_out_err([], <<-INPUT, %w[1 NameError A], [], bug3422)
BasicObject::A = 1
puts [true, false].map {|inh|
begin
Object.const_get(:A, inh)
rescue NameError => e
[e.class, e.name]
end
}
INPUT
end
def test_const_get_inherited
bug3423 = '[ruby-core:30720]'
assert_in_out_err([], <<-INPUT, %w[NameError A NameError A], [], bug3423)
module Foo; A = 1; end
class Object; include Foo; end
class Bar; include Foo; end
puts [Object, Bar].map {|klass|
begin
klass.const_get(:A, false)
rescue NameError => e
[e.class, e.name]
end
}
INPUT
end
def test_const_in_module
bug3423 = '[ruby-core:37698]'
assert_in_out_err([], <<-INPUT, %w[ok], [], bug3423)
module LangModuleSpecInObject
module LangModuleTop
end
end
include LangModuleSpecInObject
module LangModuleTop
end
puts "ok" if LangModuleSpecInObject::LangModuleTop == LangModuleTop
INPUT
bug5264 = '[ruby-core:39227]'
assert_in_out_err([], <<-'INPUT', [], [], bug5264)
class A
class X; end
end
class B < A
module X; end
end
INPUT
end
def test_class_variable_get
c = Class.new
c.class_eval('@@foo = :foo')
assert_equal(:foo, c.class_variable_get(:@@foo))
assert_raise(NameError) { c.class_variable_get(:@@bar) } # c.f. instance_variable_get
assert_raise(NameError) { c.class_variable_get(:'@@') }
assert_raise(NameError) { c.class_variable_get('@@') }
assert_raise(NameError) { c.class_variable_get(:foo) }
assert_raise(NameError) { c.class_variable_get("bar") }
assert_raise(TypeError) { c.class_variable_get(1) }
n = Object.new
def n.to_str; @count = defined?(@count) ? @count + 1 : 1; "@@foo"; end
def n.count; @count; end
assert_equal(:foo, c.class_variable_get(n))
assert_equal(1, n.count)
end
def test_class_variable_set
c = Class.new
c.class_variable_set(:@@foo, :foo)
assert_equal(:foo, c.class_eval('@@foo'))
assert_raise(NameError) { c.class_variable_set(:'@@', 1) }
assert_raise(NameError) { c.class_variable_set('@@', 1) }
assert_raise(NameError) { c.class_variable_set(:foo, 1) }
assert_raise(NameError) { c.class_variable_set("bar", 1) }
assert_raise(TypeError) { c.class_variable_set(1, 1) }
n = Object.new
def n.to_str; @count = defined?(@count) ? @count + 1 : 1; "@@foo"; end
def n.count; @count; end
c.class_variable_set(n, :bar)
assert_equal(:bar, c.class_eval('@@foo'))
assert_equal(1, n.count)
end
def test_class_variable_defined
c = Class.new
c.class_eval('@@foo = :foo')
assert_equal(true, c.class_variable_defined?(:@@foo))
assert_equal(false, c.class_variable_defined?(:@@bar))
assert_raise(NameError) { c.class_variable_defined?(:'@@') }
assert_raise(NameError) { c.class_variable_defined?('@@') }
assert_raise(NameError) { c.class_variable_defined?(:foo) }
assert_raise(NameError) { c.class_variable_defined?("bar") }
assert_raise(TypeError) { c.class_variable_defined?(1) }
n = Object.new
def n.to_str; @count = defined?(@count) ? @count + 1 : 1; "@@foo"; end
def n.count; @count; end
assert_equal(true, c.class_variable_defined?(n))
assert_equal(1, n.count)
end
def test_remove_class_variable
c = Class.new
c.class_eval('@@foo = :foo')
c.class_eval { remove_class_variable(:@@foo) }
assert_equal(false, c.class_variable_defined?(:@@foo))
end
def test_export_method
m = Module.new
assert_raise(NameError) do
m.instance_eval { public(:foo) }
end
end
def test_attr
assert_in_out_err([], <<-INPUT, %w(:ok nil), /warning: private attribute\?$/)
$VERBOSE = true
c = Class.new
c.instance_eval do
private
attr_reader :foo
end
o = c.new
o.foo rescue p(:ok)
p(o.instance_eval { foo })
INPUT
c = Class.new
assert_raise(NameError) do
c.instance_eval { attr_reader :"." }
end
end
def test_undef
c = Class.new
assert_raise(NameError) do
c.instance_eval { undef_method(:foo) }
end
m = Module.new
assert_raise(NameError) do
m.instance_eval { undef_method(:foo) }
end
o = Object.new
assert_raise(NameError) do
class << o; self; end.instance_eval { undef_method(:foo) }
end
%w(object_id __send__ initialize).each do |n|
assert_in_out_err([], <<-INPUT, [], %r"warning: undefining `#{n}' may cause serious problems$")
$VERBOSE = false
Class.new.instance_eval { undef_method(:#{n}) }
INPUT
end
end
def test_alias
m = Module.new
assert_raise(NameError) do
m.class_eval { alias foo bar }
end
assert_in_out_err([], <<-INPUT, %w(2), /discarding old foo$/)
$VERBOSE = true
c = Class.new
c.class_eval do
def foo; 1; end
def bar; 2; end
end
c.class_eval { alias foo bar }
p c.new.foo
INPUT
end
def test_mod_constants
m = Module.new
m.const_set(:Foo, :foo)
assert_equal([:Foo], m.constants(true))
assert_equal([:Foo], m.constants(false))
m.instance_eval { remove_const(:Foo) }
end
class Bug9413
class << self
Foo = :foo
end
end
def test_singleton_constants
bug9413 = '[ruby-core:59763] [Bug #9413]'
c = Bug9413.singleton_class
assert_include(c.constants(true), :Foo, bug9413)
assert_include(c.constants(false), :Foo, bug9413)
end
def test_frozen_class
m = Module.new
m.freeze
assert_raise(RuntimeError) do
m.instance_eval { undef_method(:foo) }
end
c = Class.new
c.freeze
assert_raise(RuntimeError) do
c.instance_eval { undef_method(:foo) }
end
o = Object.new
c = class << o; self; end
c.freeze
assert_raise(RuntimeError) do
c.instance_eval { undef_method(:foo) }
end
end
def test_method_defined
c = Class.new
c.class_eval do
def foo; end
def bar; end
def baz; end
public :foo
protected :bar
private :baz
end
assert_equal(true, c.public_method_defined?(:foo))
assert_equal(false, c.public_method_defined?(:bar))
assert_equal(false, c.public_method_defined?(:baz))
assert_equal(false, c.protected_method_defined?(:foo))
assert_equal(true, c.protected_method_defined?(:bar))
assert_equal(false, c.protected_method_defined?(:baz))
assert_equal(false, c.private_method_defined?(:foo))
assert_equal(false, c.private_method_defined?(:bar))
assert_equal(true, c.private_method_defined?(:baz))
end
def test_top_public_private
assert_in_out_err([], <<-INPUT, %w([:foo] [:bar]), [])
private
def foo; :foo; end
public
def bar; :bar; end
p self.private_methods.grep(/^foo$|^bar$/)
p self.methods.grep(/^foo$|^bar$/)
INPUT
end
def test_append_features
t = nil
m = Module.new
m.module_eval do
def foo; :foo; end
end
class << m; self; end.class_eval do
define_method(:append_features) do |mod|
t = mod
super(mod)
end
end
m2 = Module.new
m2.module_eval { include(m) }
assert_equal(m2, t)
o = Object.new
o.extend(m2)
assert_equal(true, o.respond_to?(:foo))
end
def test_append_features_raise
m = Module.new
m.module_eval do
def foo; :foo; end
end
class << m; self; end.class_eval do
define_method(:append_features) {|mod| raise }
end
m2 = Module.new
assert_raise(RuntimeError) do
m2.module_eval { include(m) }
end
o = Object.new
o.extend(m2)
assert_equal(false, o.respond_to?(:foo))
end
def test_append_features_type_error
assert_raise(TypeError) do
Module.new.instance_eval { append_features(1) }
end
end
def test_included
m = Module.new
m.module_eval do
def foo; :foo; end
end
class << m; self; end.class_eval do
define_method(:included) {|mod| raise }
end
m2 = Module.new
assert_raise(RuntimeError) do
m2.module_eval { include(m) }
end
o = Object.new
o.extend(m2)
assert_equal(true, o.respond_to?(:foo))
end
def test_cyclic_include
m1 = Module.new
m2 = Module.new
m1.instance_eval { include(m2) }
assert_raise(ArgumentError) do
m2.instance_eval { include(m1) }
end
end
def test_include_p
m = Module.new
c1 = Class.new
c1.instance_eval { include(m) }
c2 = Class.new(c1)
assert_equal(true, c1.include?(m))
assert_equal(true, c2.include?(m))
assert_equal(false, m.include?(m))
end
def test_send
a = AClass.new
assert_equal(:aClass, a.__send__(:aClass))
assert_equal(:aClass1, a.__send__(:aClass1))
assert_equal(:aClass2, a.__send__(:aClass2))
b = BClass.new
assert_equal(:aClass, b.__send__(:aClass))
assert_equal(:aClass1, b.__send__(:aClass1))
assert_equal(:aClass2, b.__send__(:aClass2))
assert_equal(:bClass1, b.__send__(:bClass1))
assert_equal(:bClass2, b.__send__(:bClass2))
assert_equal(:bClass3, b.__send__(:bClass3))
end
def test_nonascii_name
c = eval("class ::C\u{df}; self; end")
assert_equal("C\u{df}", c.name, '[ruby-core:24600]')
c = eval("class C\u{df}; self; end")
assert_equal("TestModule::C\u{df}", c.name, '[ruby-core:24600]')
end
def test_method_added
memo = []
mod = Module.new do
mod = self
(class << self ; self ; end).class_eval do
define_method :method_added do |sym|
memo << sym
memo << mod.instance_methods(false)
memo << (mod.instance_method(sym) rescue nil)
end
end
def f
end
alias g f
attr_reader :a
attr_writer :a
end
assert_equal :f, memo.shift
assert_equal [:f], memo.shift, '[ruby-core:25536]'
assert_equal mod.instance_method(:f), memo.shift
assert_equal :g, memo.shift
assert_equal [:f, :g], memo.shift
assert_equal mod.instance_method(:f), memo.shift
assert_equal :a, memo.shift
assert_equal [:f, :g, :a], memo.shift
assert_equal mod.instance_method(:a), memo.shift
assert_equal :a=, memo.shift
assert_equal [:f, :g, :a, :a=], memo.shift
assert_equal mod.instance_method(:a=), memo.shift
end
def test_method_undefined
added = []
undefed = []
removed = []
mod = Module.new do
mod = self
def f
end
(class << self ; self ; end).class_eval do
define_method :method_added do |sym|
added << sym
end
define_method :method_undefined do |sym|
undefed << sym
end
define_method :method_removed do |sym|
removed << sym
end
end
end
assert_method_defined?(mod, :f)
mod.module_eval do
undef :f
end
assert_equal [], added
assert_equal [:f], undefed
assert_equal [], removed
end
def test_method_removed
added = []
undefed = []
removed = []
mod = Module.new do
mod = self
def f
end
(class << self ; self ; end).class_eval do
define_method :method_added do |sym|
added << sym
end
define_method :method_undefined do |sym|
undefed << sym
end
define_method :method_removed do |sym|
removed << sym
end
end
end
assert_method_defined?(mod, :f)
mod.module_eval do
remove_method :f
end
assert_equal [], added
assert_equal [], undefed
assert_equal [:f], removed
end
def test_method_redefinition
feature2155 = '[ruby-dev:39400]'
line = __LINE__+4
stderr = EnvUtil.verbose_warning do
Module.new do
def foo; end
def foo; end
end
end
assert_match(/:#{line}: warning: method redefined; discarding old foo/, stderr)
assert_match(/:#{line-1}: warning: previous definition of foo/, stderr, feature2155)
assert_warning '' do
Module.new do
def foo; end
alias bar foo
def foo; end
end
end
assert_warning '' do
Module.new do
def foo; end
alias bar foo
alias bar foo
end
end
line = __LINE__+4
stderr = EnvUtil.verbose_warning do
Module.new do
define_method(:foo) do end
def foo; end
end
end
assert_match(/:#{line}: warning: method redefined; discarding old foo/, stderr)
assert_match(/:#{line-1}: warning: previous definition of foo/, stderr, feature2155)
assert_warning '' do
Module.new do
define_method(:foo) do end
alias bar foo
alias bar foo
end
end
assert_warning('', '[ruby-dev:39397]') do
Module.new do
module_function
def foo; end
module_function :foo
end
end
assert_warning '' do
Module.new do
def foo; end
undef foo
end
end
end
def test_protected_singleton_method
klass = Class.new
x = klass.new
class << x
protected
def foo
end
end
assert_raise(NoMethodError) do
x.foo
end
klass.send(:define_method, :bar) do
x.foo
end
assert_nothing_raised do
x.bar
end
y = klass.new
assert_raise(NoMethodError) do
y.bar
end
end
def test_uninitialized_toplevel_constant
bug3123 = '[ruby-dev:40951]'
e = assert_raise(NameError) {eval("Bug3123", TOPLEVEL_BINDING)}
assert_not_match(/Object::/, e.message, bug3123)
end
def test_attr_inherited_visibility
bug3406 = '[ruby-core:30638]'
c = Class.new do
class << self
private
def attr_accessor(*); super; end
end
attr_accessor :x
end.new
assert_nothing_raised(bug3406) {c.x = 1}
assert_equal(1, c.x, bug3406)
end
def test_attr_writer_with_no_arguments
bug8540 = "[ruby-core:55543]"
c = Class.new do
attr_writer :foo
end
assert_raise(ArgumentError) { c.new.send :foo= }
end
def test_private_constant
c = Class.new
c.const_set(:FOO, "foo")
assert_equal("foo", c::FOO)
c.private_constant(:FOO)
assert_raise(NameError) { c::FOO }
assert_equal("foo", c.class_eval("FOO"))
assert_equal("foo", c.const_get("FOO"))
$VERBOSE, verbose = nil, $VERBOSE
c.const_set(:FOO, "foo")
$VERBOSE = verbose
assert_raise(NameError) { c::FOO }
end
def test_private_constant2
c = Class.new
c.const_set(:FOO, "foo")
c.const_set(:BAR, "bar")
assert_equal("foo", c::FOO)
assert_equal("bar", c::BAR)
c.private_constant(:FOO, :BAR)
assert_raise(NameError) { c::FOO }
assert_raise(NameError) { c::BAR }
assert_equal("foo", c.class_eval("FOO"))
assert_equal("bar", c.class_eval("BAR"))
end
def test_private_constant_with_no_args
assert_in_out_err([], <<-RUBY, [], ["-:3: warning: private_constant with no argument is just ignored"])
$-w = true
class X
private_constant
end
RUBY
end
class PrivateClass
end
private_constant :PrivateClass
def test_define_module_under_private_constant
assert_raise(NameError) do
eval %q{class TestModule::PrivateClass; end}
end
assert_raise(NameError) do
eval %q{module TestModule::PrivateClass::TestModule; end}
end
eval %q{class PrivateClass; end}
eval %q{module PrivateClass::TestModule; end}
assert_instance_of(Module, PrivateClass::TestModule)
PrivateClass.class_eval { remove_const(:TestModule) }
end
def test_public_constant
c = Class.new
c.const_set(:FOO, "foo")
assert_equal("foo", c::FOO)
c.private_constant(:FOO)
assert_raise(NameError) { c::FOO }
assert_equal("foo", c.class_eval("FOO"))
c.public_constant(:FOO)
assert_equal("foo", c::FOO)
end
def test_constants_with_private_constant
assert_not_include(::TestModule.constants, :PrivateClass)
end
def test_toplevel_private_constant
src = <<-INPUT
class Object
private_constant :Object
end
p Object
begin
p ::Object
rescue
p :ok
end
INPUT
assert_in_out_err([], src, %w(Object :ok), [])
end
def test_private_constants_clear_inlinecache
bug5702 = '[ruby-dev:44929]'
src = <<-INPUT
class A
C = :Const
def self.get_C
A::C
end
# fill cache
A.get_C
private_constant :C, :D rescue nil
begin
A.get_C
rescue NameError
puts "A.get_C"
end
end
INPUT
assert_in_out_err([], src, %w(A.get_C), [], bug5702)
end
def test_constant_lookup_in_method_defined_by_class_eval
src = <<-INPUT
class A
B = 42
end
A.class_eval do
def self.f
B
end
def f
B
end
end
begin
A.f
rescue NameError
puts "A.f"
end
begin
A.new.f
rescue NameError
puts "A.new.f"
end
INPUT
assert_in_out_err([], src, %w(A.f A.new.f), [])
end
def test_constant_lookup_in_toplevel_class_eval
src = <<-INPUT
module X
A = 123
end
begin
X.class_eval { A }
rescue NameError => e
puts e
end
INPUT
assert_in_out_err([], src, ["uninitialized constant A"], [])
end
def test_constant_lookup_in_module_in_class_eval
src = <<-INPUT
class A
B = 42
end
A.class_eval do
module C
begin
B
rescue NameError
puts "NameError"
end
end
end
INPUT
assert_in_out_err([], src, ["NameError"], [])
end
module M0
def m1; [:M0] end
end
module M1
def m1; [:M1, *super] end
end
module M2
def m1; [:M2, *super] end
end
M3 = Module.new do
def m1; [:M3, *super] end
end
module M4
def m1; [:M4, *super] end
end
class C
def m1; end
end
class C0 < C
include M0
prepend M1
def m1; [:C0, *super] end
end
class C1 < C0
prepend M2, M3
include M4
def m1; [:C1, *super] end
end
def test_prepend
obj = C0.new
expected = [:M1,:C0,:M0]
assert_equal(expected, obj.m1)
obj = C1.new
expected = [:M2,:M3,:C1,:M4,:M1,:C0,:M0]
assert_equal(expected, obj.m1)
end
def test_public_prepend
assert_nothing_raised('#8846') do
Class.new.prepend(Module.new)
end
end
def test_prepend_inheritance
bug6654 = '[ruby-core:45914]'
a = labeled_module("a")
b = labeled_module("b") {include a}
c = labeled_class("c") {prepend b}
assert_operator(c, :<, b, bug6654)
assert_operator(c, :<, a, bug6654)
bug8357 = '[ruby-core:54736] [Bug #8357]'
b = labeled_module("b") {prepend a}
c = labeled_class("c") {include b}
assert_operator(c, :<, b, bug8357)
assert_operator(c, :<, a, bug8357)
bug8357 = '[ruby-core:54742] [Bug #8357]'
assert_kind_of(b, c.new, bug8357)
end
def test_prepend_instance_methods
bug6655 = '[ruby-core:45915]'
assert_equal(Object.instance_methods, Class.new {prepend Module.new}.instance_methods, bug6655)
end
def test_prepend_singleton_methods
o = Object.new
o.singleton_class.class_eval {prepend Module.new}
assert_equal([], o.singleton_methods)
end
def test_prepend_remove_method
c = Class.new do
prepend Module.new {def foo; end}
end
assert_raise(NameError) do
c.class_eval do
remove_method(:foo)
end
end
c.class_eval do
def foo; end
end
removed = nil
c.singleton_class.class_eval do
define_method(:method_removed) {|id| removed = id}
end
assert_nothing_raised(NoMethodError, NameError, '[Bug #7843]') do
c.class_eval do
remove_method(:foo)
end
end
assert_equal(:foo, removed)
end
def test_prepend_class_ancestors
bug6658 = '[ruby-core:45919]'
m = labeled_module("m")
c = labeled_class("c") {prepend m}
assert_equal([m, c], c.ancestors[0, 2], bug6658)
bug6662 = '[ruby-dev:45868]'
c2 = labeled_class("c2", c)
anc = c2.ancestors
assert_equal([c2, m, c, Object], anc[0..anc.index(Object)], bug6662)
end
def test_prepend_module_ancestors
bug6659 = '[ruby-dev:45861]'
m0 = labeled_module("m0") {def x; [:m0, *super] end}
m1 = labeled_module("m1") {def x; [:m1, *super] end; prepend m0}
m2 = labeled_module("m2") {def x; [:m2, *super] end; prepend m1}
c0 = labeled_class("c0") {def x; [:c0] end}
c1 = labeled_class("c1") {def x; [:c1] end; prepend m2}
c2 = labeled_class("c2", c0) {def x; [:c2, *super] end; include m2}
assert_equal([m0, m1], m1.ancestors, bug6659)
bug6662 = '[ruby-dev:45868]'
assert_equal([m0, m1, m2], m2.ancestors, bug6662)
assert_equal([m0, m1, m2, c1], c1.ancestors[0, 4], bug6662)
assert_equal([:m0, :m1, :m2, :c1], c1.new.x)
assert_equal([c2, m0, m1, m2, c0], c2.ancestors[0, 5], bug6662)
assert_equal([:c2, :m0, :m1, :m2, :c0], c2.new.x)
m3 = labeled_module("m3") {include m1; prepend m1}
assert_equal([m3, m0, m1], m3.ancestors)
m3 = labeled_module("m3") {prepend m1; include m1}
assert_equal([m0, m1, m3], m3.ancestors)
m3 = labeled_module("m3") {prepend m1; prepend m1}
assert_equal([m0, m1, m3], m3.ancestors)
m3 = labeled_module("m3") {include m1; include m1}
assert_equal([m3, m0, m1], m3.ancestors)
end
def labeled_module(name, &block)
EnvUtil.labeled_module(name, &block)
end
def labeled_class(name, superclass = Object, &block)
EnvUtil.labeled_class(name, superclass, &block)
end
def test_prepend_instance_methods_false
bug6660 = '[ruby-dev:45863]'
assert_equal([:m1], Class.new{ prepend Module.new; def m1; end }.instance_methods(false), bug6660)
assert_equal([:m1], Class.new(Class.new{def m2;end}){ prepend Module.new; def m1; end }.instance_methods(false), bug6660)
end
def test_cyclic_prepend
bug7841 = '[ruby-core:52205] [Bug #7841]'
m1 = Module.new
m2 = Module.new
m1.instance_eval { prepend(m2) }
assert_raise(ArgumentError, bug7841) do
m2.instance_eval { prepend(m1) }
end
end
def test_prepend_optmethod
bug7983 = '[ruby-dev:47124] [Bug #7983]'
assert_separately [], %{
module M
def /(other)
to_f / other
end
end
Fixnum.send(:prepend, M)
assert_equal(0.5, 1 / 2, "#{bug7983}")
}
assert_equal(0, 1 / 2)
end
def test_prepend_visibility
bug8005 = '[ruby-core:53106] [Bug #8005]'
c = Class.new do
prepend Module.new {}
def foo() end
protected :foo
end
a = c.new
assert_respond_to a, [:foo, true], bug8005
assert_nothing_raised(NoMethodError, bug8005) {a.send :foo}
end
def test_prepend_visibility_inherited
bug8238 = '[ruby-core:54105] [Bug #8238]'
assert_separately [], <<-"end;", timeout: 10
class A
def foo() A; end
private :foo
end
class B < A
public :foo
prepend Module.new
end
assert_equal(A, B.new.foo, "#{bug8238}")
end;
end
def test_prepend_included_modules
bug8025 = '[ruby-core:53158] [Bug #8025]'
mixin = labeled_module("mixin")
c = labeled_module("c") {prepend mixin}
im = c.included_modules
assert_not_include(im, c, bug8025)
assert_include(im, mixin, bug8025)
c1 = labeled_class("c1") {prepend mixin}
c2 = labeled_class("c2", c1)
im = c2.included_modules
assert_not_include(im, c1, bug8025)
assert_not_include(im, c2, bug8025)
assert_include(im, mixin, bug8025)
end
def test_prepend_super_in_alias
bug7842 = '[Bug #7842]'
p = labeled_module("P") do
def m; "P"+super; end
end
a = labeled_class("A") do
def m; "A"; end
end
b = labeled_class("B", a) do
def m; "B"+super; end
alias m2 m
prepend p
alias m3 m
end
assert_equal("BA", b.new.m2, bug7842)
assert_equal("PBA", b.new.m3, bug7842)
end
def test_include_super_in_alias
bug9236 = '[Bug #9236]'
fun = labeled_module("Fun") do
def hello
orig_hello
end
end
m1 = labeled_module("M1") do
def hello
'hello!'
end
end
m2 = labeled_module("M2") do
def hello
super
end
end
foo = labeled_class("Foo") do
include m1
include m2
alias orig_hello hello
include fun
end
assert_equal('hello!', foo.new.hello, bug9236)
end
def test_class_variables
m = Module.new
m.class_variable_set(:@@foo, 1)
m2 = Module.new
m2.send(:include, m)
m2.class_variable_set(:@@bar, 2)
assert_equal([:@@foo], m.class_variables)
assert_equal([:@@bar, :@@foo], m2.class_variables)
assert_equal([:@@bar, :@@foo], m2.class_variables(true))
assert_equal([:@@bar], m2.class_variables(false))
end
Bug6891 = '[ruby-core:47241]'
def test_extend_module_with_protected_method
list = []
x = Class.new {
@list = list
extend Module.new {
protected
def inherited(klass)
@list << "protected"
super(klass)
end
}
extend Module.new {
def inherited(klass)
@list << "public"
super(klass)
end
}
}
assert_nothing_raised(NoMethodError, Bug6891) {Class.new(x)}
assert_equal(['public', 'protected'], list)
end
def test_extend_module_with_protected_bmethod
list = []
x = Class.new {
extend Module.new {
protected
define_method(:inherited) do |klass|
list << "protected"
super(klass)
end
}
extend Module.new {
define_method(:inherited) do |klass|
list << "public"
super(klass)
end
}
}
assert_nothing_raised(NoMethodError, Bug6891) {Class.new(x)}
assert_equal(['public', 'protected'], list)
end
def test_invalid_attr
%W[
foo?
@foo
@@foo
$foo
\u3042$
].each do |name|
assert_raise_with_message(NameError, /#{Regexp.quote(quote(name))}/) do
Module.new { attr_accessor name.to_sym }
end
end
end
private def quote(name)
encoding = Encoding.default_internal || Encoding.default_external
(name.encoding == encoding || name.ascii_only?) ? name : name.inspect
end
class AttrTest
class << self
attr_accessor :cattr
end
attr_accessor :iattr
def ivar
@ivar
end
end
def test_uninitialized_instance_variable
a = AttrTest.new
assert_warning(/instance variable @ivar not initialized/) do
assert_nil(a.ivar)
end
a.instance_variable_set(:@ivar, 42)
assert_warning '' do
assert_equal(42, a.ivar)
end
end
def test_uninitialized_attr
a = AttrTest.new
assert_warning '' do
assert_nil(a.iattr)
end
a.iattr = 42
assert_warning '' do
assert_equal(42, a.iattr)
end
end
def test_uninitialized_attr_class
assert_warning '' do
assert_nil(AttrTest.cattr)
end
AttrTest.cattr = 42
assert_warning '' do
assert_equal(42, AttrTest.cattr)
end
end
def test_uninitialized_attr_non_object
a = Class.new(Array) do
attr_accessor :iattr
end.new
assert_warning '' do
assert_nil(a.iattr)
end
a.iattr = 42
assert_warning '' do
assert_equal(42, a.iattr)
end
end
def test_remove_const
m = Module.new
assert_raise(NameError){ m.instance_eval { remove_const(:__FOO__) } }
end
def test_private_top_methods
assert_top_method_is_private(:include)
assert_top_method_is_private(:public)
assert_top_method_is_private(:private)
assert_top_method_is_private(:define_method)
end
module PrivateConstantReopen
PRIVATE_CONSTANT = true
private_constant :PRIVATE_CONSTANT
end
def test_private_constant_reopen
assert_raise(NameError) do
eval <<-EOS, TOPLEVEL_BINDING
module TestModule::PrivateConstantReopen::PRIVATE_CONSTANT
end
EOS
end
assert_raise(NameError) do
eval <<-EOS, TOPLEVEL_BINDING
class TestModule::PrivateConstantReopen::PRIVATE_CONSTANT
end
EOS
end
end
def test_singleton_class_ancestors
feature8035 = '[ruby-core:53171]'
obj = Object.new
assert_equal [obj.singleton_class, Object], obj.singleton_class.ancestors.first(2), feature8035
mod = Module.new
obj.extend mod
assert_equal [obj.singleton_class, mod, Object], obj.singleton_class.ancestors.first(3)
obj = Object.new
obj.singleton_class.send :prepend, mod
assert_equal [mod, obj.singleton_class, Object], obj.singleton_class.ancestors.first(3)
end
def test_visibility_by_public_class_method
bug8284 = '[ruby-core:54404] [Bug #8284]'
assert_raise(NoMethodError) {Object.define_method}
Module.new.public_class_method(:define_method)
assert_raise(NoMethodError, bug8284) {Object.define_method}
end
def test_include_module_with_constants_invalidates_method_cache
assert_in_out_err([], <<-RUBY, %w(123 456), [])
A = 123
class Foo
def self.a
A
end
end
module M
A = 456
end
puts Foo.a
Foo.send(:include, M)
puts Foo.a
RUBY
end
def test_return_value_of_define_method
retvals = []
Class.new.class_eval do
retvals << define_method(:foo){}
retvals << define_method(:bar, instance_method(:foo))
end
assert_equal :foo, retvals[0]
assert_equal :bar, retvals[1]
end
def test_return_value_of_define_singleton_method
retvals = []
Class.new do
retvals << define_singleton_method(:foo){}
retvals << define_singleton_method(:bar, method(:foo))
end
assert_equal :foo, retvals[0]
assert_equal :bar, retvals[1]
end
def test_prepend_gc
assert_separately [], %{
module Foo
end
class Object
prepend Foo
end
GC.start # make created T_ICLASS old (or remembered shady)
class Object # add methods into T_ICLASS (need WB if it is old)
def foo; end
attr_reader :bar
end
1_000_000.times{''} # cause GC
}
end
private
def assert_top_method_is_private(method)
assert_separately [], %{
methods = singleton_class.private_instance_methods(false)
assert_include(methods, :#{method}, ":#{method} should be private")
assert_raise_with_message(NoMethodError, "private method `#{method}' called for main:Object") {
self.#{method}
}
}
end
end
| 25.203751 | 125 | 0.635289 |
388057ae079e683e476bb0970288d9de9d752b0f | 870 | Уведомления о недобросовестных интернет-магазинах будут распространяться среди москвичей.
В Москве выйдет уведомление о том, как избежать стать жертвой интернет-магазина.
Об этом сообщил Роспотребнадзор, пишет М24.
Сообщается, что эксперты агентства готовят уведомление, которое поможет гражданам правильно выбрать интернет-магазин и распознать, возможно, мошеннические схемы.
Цель этой брошюры - охватить несколько разделов.
Они будут включать общую информацию и правовые рамки, условия поставки товаров и способы защиты своих юридических прав.
Рекомендации о том, как правильно подать жалобу и т. Д., Будут включены в приложение », - сказал Роспотребнадзор.
На данный момент уведомление завершается.
Впоследствии он будет размещен на веб-сайте Департамента Роспотребнадзора г. Москвы, а также планируется выпустить печатную версию и распространить ее среди москвичей.
| 87 | 167 | 0.83908 |
1a6352831981974f577212b4aa05733eaa402bb7 | 175 | require 'models_data'
class UploadModels < UploadCsvFile
def initialize_data(path)
@data = ModelsData.new(
path, @csv_upload.user, encoding(path)
)
end
end
| 17.5 | 44 | 0.702857 |
2860f751b3aa4edbe713624f8c1310abccc92a17 | 551 | class DropNotifications < ActiveRecord::Migration[4.2]
def up
drop_table :notifications
end
def down
create_table :notifications do |t|
t.string :title, null: false
t.text :body, null: false
t.string :state, default: 'draft', null: false
t.integer :comments_count, default: 0, null: false
t.integer :user_id
t.string :post_type
t.string :author
t.text :introduction
t.boolean :deleted, default: false, null: false
t.timestamps null: false
end
end
end
| 26.238095 | 57 | 0.631579 |
1af8e485d540822c75c76a40e91a0abf37a9c6c1 | 2,815 | class User < ApplicationRecord
has_many :microposts, dependent: :destroy
attr_accessor :remember_token, :activation_token, :reset_token
before_save :downcase_email
before_create :create_activation_digest
validates :name, presence: true, length: { maximum: 50 }
VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-]+(\.[a-z\d\-]+)*\.[a-z]+\z/i
validates :email, presence: true, length: { maximum: 255 },
format: { with: VALID_EMAIL_REGEX },
uniqueness: { case_sensitive: false }
has_secure_password
validates :password, presence: true, length: { minimum: 6 }, allow_nil: true
# Returns true if the given token matches the digest.
def authenticated?(attribute, token)
digest = send("#{attribute}_digest")
return false if digest.nil?
BCrypt::Password.new(digest).is_password?(token)
end
# Returns the hash digest of the given string.
def self.digest(string)
cost = ActiveModel::SecurePassword.min_cost ? BCrypt::Engine::MIN_COST :
BCrypt::Engine.cost
BCrypt::Password.create(string, cost: cost)
end
# Returns a random token.
def User.new_token
SecureRandom.urlsafe_base64
end
# Remembers a user in the database for use in persistent sessions.
def remember
self.remember_token = User.new_token
update_attribute(:remember_digest, User.digest(remember_token))
end
# Returns true if the given token matches the digest.
def authenticated?(attribute, token)
digest = send("#{attribute}_digest")
return false if digest.nil?
BCrypt::Password.new(digest).is_password?(token)
end
# Forgets a user.
def forget
update_attribute(:remember_digest, nil)
end
# Sets the password reset attributes.
def create_reset_digest
self.reset_token = User.new_token
update_attribute(:reset_digest, User.digest(reset_token))
update_attribute(:reset_sent_at, Time.zone.now)
end
# Sends password reset email.
def send_password_reset_email
UserMailer.password_reset(self).deliver_now
end
# Activates an account.
def activate
update_attribute(:activated, true)
update_attribute(:activated_at, Time.zone.now)
end
# Sends activation email.
def send_activation_email
UserMailer.account_activation(self).deliver_now
end
# Returns true if a password reset has expired.
def password_reset_expired?
reset_sent_at < 2.hours.ago
end
# Defines a proto-feed.
# See "Following users" for the full implementation.
def feed
Micropost.where("user_id = ?", id)
end
private
def downcase_email
self.email = email.downcase
end
def create_activation_digest
self.activation_token = User.new_token
self.activation_digest = User.digest(activation_token)
end
end
| 29.020619 | 78 | 0.702309 |
ac6a9b11d97be9b02a0b31b04b5a8e3e237b7ef4 | 91 | json.extract! @web_config, :id, :directory, :scan_interval, :old, :created_at, :updated_at
| 45.5 | 90 | 0.747253 |
6a9089bccf47d9a752281313390df2590c7e6867 | 3,894 | require "active_support"
require "mechanize"
require 'openssl'
class EveGate
class Mail
attr_accessor :receipient, :subject, :read
#attr_writer :body, :sender, :to
def initialize(mail, agent)
@read = mail.children[2].children[1].attributes['alt'].text == 'Read'
@sender = mail.children[4].children[1].text.strip
@subject = mail.children[6].children[1].children[1].text
@url = mail.children[6].children[1].children[1].attributes['href'].value
@date = DateTime.parse(mail.children[8].text).to_time
@agent = agent
end
def body
update_details unless @body
@body
end
def sender
update_details unless @sender
@sender
end
def to
update_details unless @to
@to
end
def update_details
@agent.get(@url)
@body = @agent.page.search(".//div[@id='hideBottomButtons']/p")[1].inner_html
@to = @agent.page.search(".//div[@id='hideBottomButtons']/p[1]/a")[1].text
@sender = @agent.page.search(".//div[@id='hideBottomButtons']/p[1]/a")[0].text
end
end
def initialize(user, pass, character)
@user = user
@pass = pass
@character = character
@agent = Mechanize.new
@page = nil
@characters = {}
login
end
def login
begin
@page = @agent.get('https://www.evegate.com/')
rescue Mechanize::ResponseCodeError
puts "EveGate is currently not available."
exit -1
end
login_form = @page.form_with(:action => "/LogOn/Logon")
login_form['username'] = @user
login_form['password'] = @pass
@agent.submit(login_form, login_form.button_with(:value => 'Log On'))
if error = @agent.page.search(".//ul[@class='logOnErrorMessages']/li")
if error.text.include? 'EVE Gate is currently not accepting new logins'
puts "EVE Gate is currently not accepting new logins"
exit -1
end
end
if @agent.page.links_with(:href => /\/Account\/SwitchCharacter\?characterName=#{@character.gsub(' ', '%20')}/).length != 0
puts "switch char"
@agent.page.links_with(:href => /\/Account\/SwitchCharacter\?characterName=#{@character.gsub(' ', '%20')}/)[0].click
end
if @agent.page.links_with(:href => /\/Account\/LogOnCharacter\?characterName=#{@character.gsub(' ', '%20')}/).length != 0
puts "logong char"
@agent.page.links_with(:href => /\/Account\/LogOnCharacter\?characterName=#{@character.gsub(' ', '%20')}/)[0].click
end
if @character != current_character
raise "Could not select #{@character}."
end
end
def eve_mails
@agent.get('/Mail/Inbox')
parse_mails
end
def corporation_mails
@agent.get('/Mail/Corp')
parse_mails
end
def alliance_mails
@agent.get('/Mail/Alliance')
parse_mails
end
def send_mail(to, subject, text)
@agent.get('/Mail/Compose')
mail_form = @agent.page.forms_with(:action => "/Mail/SendMessage").first
mail_form['recipientLine'] = to
mail_form['subject'] = subject
mail_form['message'] = text
mail_form['mailContents'] = text
@agent.submit(mail_form, mail_form.button_with(:value => 'Send'))
@agent.page.code == "200"
end
def current_character
begin
c1 = @agent.page.search(".//div[@id='activeCharacterContent']/div/div/h1").text
return c1 if c1 != ""
c2 = @agent.page.search(".//div[@id='sectionHeaderContainer']/div/span").text.gsub(' Contacts Chatter','')
return c2 if c2 != ""
rescue
raise "Error getting current character."
end
end
private
def dump_page
File.open('page', 'w') { |f| f.write @agent.page.parser }
end
def parse_mails
mails = []
@agent.page.search(".//table[@id='mailTable']/tbody/tr").each do |mail|
mails << Mail.new(mail, @agent)
end
mails
end
end | 29.059701 | 126 | 0.616846 |
268858ccac8971e285db6a3a9ecdf7a1183ff53c | 780 | require 'minitest/spec'
describe_recipe 'apache2::mod_python' do
include MiniTest::Chef::Resources
include MiniTest::Chef::Assertions
before :all do
@prefix = case node[:platform_family]
when 'rhel'
node[:apache][:dir]
when "debian"
".."
end
end
it 'installs dependencies' do
case node[:platform]
when 'debian','ubuntu'
package('libapache2-mod-python').must_be_installed
when 'centos','redhat','fedora','amazon'
package('mod_python').must_be_installed
end
end
it 'enables mod_python' do
link("#{node[:apache][:dir]}/mods-enabled/python.load").must_exist.with(
:link_type, :symbolic).and(:to, "#{@prefix}/mods-available/python.load")
end
end
| 26 | 81 | 0.620513 |
bf80b29a1d6bf568d21ec15ec9d00343dc4af43d | 886 | require 'spec_helper'
describe ManualPayment do
before do
@pay = described_class.new
end
describe "when a registrant has been added" do
let(:registrant) { FactoryBot.create(:competitor) }
let(:expense_item) { FactoryBot.create :expense_item, cost: 10.00, tax: 2.00 }
let!(:registrant_expense_item) { FactoryBot.create :registrant_expense_item, line_item: expense_item, registrant: registrant }
before do
@pay.add_registrant(registrant.reload)
@pay.unpaid_details.first.pay_for = true
end
it "lists the unpaid items for the registrant" do
expect(@pay.unpaid_details.size).to eq(1)
end
describe "with a built payment" do
let(:payment) { @pay.build_payment }
it "sets the payment_detail to the total cost" do
expect(payment.payment_details.first.amount).to eq 12.00.to_money
end
end
end
end
| 28.580645 | 130 | 0.702032 |
1a11c7563771e31acd6ca5bd335dbfeef974533f | 240 | class Gallery < Actor
has_many :locations, :as => :addressable
has_many :exhibitions, :as => :organizer
has_many :transactions, :as => :recipient
has_many :transactions, :as => :supplier
validates_presence_of :name
end | 26.666667 | 45 | 0.691667 |
6289230e20c1066065bbb1908162f6fc8e9df4c6 | 968 | describe SwitchmanInstJobs::Delayed::MessageSending do
shared_examples_for 'batch jobs sharding' do
it 'should keep track of the current shard on child jobs' do
project.shard.activate do
::Delayed::Batch.serial_batch do
expect(
'string'.delay(ignore_transaction: true).size
).to be true
expect(
'string'.delay(ignore_transaction: true).gsub(/./, '!')
).to be true
end
end
job = ::Delayed::Job.find_available(1).first
expect(job.current_shard).to eq project.shard
expect(job.payload_object.jobs.first.current_shard).to eq project.shard
end
end
context 'unsharded project' do
let(:project) { Project.create! }
include_examples 'batch jobs sharding'
end
context 'sharded project' do
include Switchman::RSpecHelper
let(:project) { @shard1.activate { Project.create! } }
include_examples 'batch jobs sharding'
end
end
| 28.470588 | 77 | 0.658058 |
1c393bf45bf6e49cb5dca5238cfd0f0b63a37202 | 428 | cask 'gearsystem' do
version '3.0.2'
sha256 '23559909818aaa99f8e1d87cc944583bd9ffaa8ad77a1e2f6a284a465700ee4f'
url "https://github.com/drhelius/Gearsystem/releases/download/gearsystem-#{version}/Gearsystem-#{version}-macOS.zip"
appcast 'https://github.com/drhelius/Gearsystem/releases.atom'
name 'Gearsystem'
homepage 'https://github.com/drhelius/Gearsystem'
app "Gearsystem-#{version}-macOS/Gearsystem.app"
end
| 35.666667 | 118 | 0.78271 |
87904845a96b8dd481c9d1428959312e81f8ab55 | 213 | class CreateComments < ActiveRecord::Migration[5.2]
def change
create_table :comments do |t|
t.string :content
t.integer :league_id
t.integer :team_id
t.timestamps
end
end
end
| 17.75 | 51 | 0.657277 |
334528e3dd3df9e4b1d2c5c4ec20ab5c4b7fd9dd | 3,465 | require 'metasm'
require 'erb'
require 'metasploit/framework/compiler/utils'
require 'metasploit/framework/compiler/headers/windows'
require 'metasploit/framework/obfuscation/crandomizer'
module Metasploit
module Framework
module Compiler
class Windows
# Returns the binary of a compiled source.
#
# @param c_template [String] The C source code to compile.
# @param type [Symbol] PE type, either :exe or :dll
# @param cpu [Metasm::CPU] A Metasm cpu object, for example: Metasm::Ia32.new
# @raise [NotImplementedError] If the type is not supported.
# @return [String] The compiled code.
def self.compile_c(c_template, type=:exe, cpu=Metasm::Ia32.new)
headers = Compiler::Headers::Windows.new
source_code = Compiler::Utils.normalize_code(c_template, headers)
pe = Metasm::PE.compile_c(cpu, source_code)
case type
when :exe
pe.encode
when :dll
pe.encode('dll')
else
raise NotImplementedError
end
end
# Saves the compiled code as a file. This is basically a wrapper of #self.compile.
#
# @param out_file [String] The file path to save the binary as.
# @param c_template [String] The C source code to compile.
# @param type [Symbol] PE type, either :exe or :dll
# @param cpu [Metasm::CPU] A Metasm cpu object, for example: Metasm::Ia32.new
# @return [Integer] The number of bytes written.
def self.compile_c_to_file(out_file, c_template, type=:exe, cpu=Metasm::Ia32.new)
pe = self.compile_c(c_template, type)
File.write(out_file, pe)
end
# Returns randomized c source code.
#
# @param c_template [String]
#
# @raise [NotImplementedError] If the type is not supported.
# @return [String] The compiled code.
def self.generate_random_c(c_template, opts={})
weight = opts[:weight] || 80
headers = Compiler::Headers::Windows.new
source_code = Compiler::Utils.normalize_code(c_template, headers)
randomizer = Metasploit::Framework::Obfuscation::CRandomizer::Parser.new(weight)
randomized_code = randomizer.parse(source_code)
randomized_code.to_s
end
# Returns the binary of a randomized and compiled source code.
#
# @param c_template [String]
#
# @raise [NotImplementedError] If the type is not supported.
# @return [String] The compiled code.
def self.compile_random_c(c_template, opts={})
type = opts[:type] || :exe
cpu = opts[:cpu] || Metasm::Ia32.new
random_c = self.generate_random_c(c_template, opts)
self.compile_c(random_c, type, cpu)
end
# Saves the randomized compiled code as a file. This is basically a wrapper for #self.compile_random_c
#
# @param out_file [String] The file path to save the binary as.
# @param c_template [String] The randomized C source code to compile.
# @param opts [Hash] Options to pass to #compile_random_c
# @return [Integer] The number of bytes written.
def self.compile_random_c_to_file(out_file, c_template, opts={})
pe = self.compile_random_c(c_template, opts)
File.write(out_file, pe)
end
end
end
end
end
| 37.663043 | 110 | 0.627417 |
6af64610b4df7f21f2acae843ac943c41cc6b9bf | 1,167 | cask 'rider' do
version '2020.1.0,201.6668.197'
sha256 '18ec5af9491654c159cae1386748d7653c5e9e596db30a58222acec2730c9d27'
url "https://download.jetbrains.com/rider/JetBrains.Rider-#{version.before_comma}.dmg"
appcast 'https://data.services.jetbrains.com/products/releases?code=RD&latest=true&type=release'
name 'Jetbrains Rider'
homepage 'https://www.jetbrains.com/rider/'
auto_updates true
app 'Rider.app'
uninstall_postflight do
ENV['PATH'].split(File::PATH_SEPARATOR).map { |path| File.join(path, 'rider') }.each { |path| File.delete(path) if File.exist?(path) && File.readlines(path).grep(%r{# see com.intellij.idea.SocketLock for the server side of this interface}).any? }
end
zap trash: [
"~/Library/Application Support/Rider#{version.major_minor}",
"~/Library/Caches/Rider#{version.major_minor}",
"~/Library/Logs/Rider#{version.major_minor}",
"~/Library/Preferences/Rider#{version.major_minor}",
'~/Library/Preferences/jetbrains.rider.71e559ef.plist',
'~/Library/Saved Application State/com.jetbrains.rider.savedState',
]
end
| 43.222222 | 250 | 0.685518 |
876f1aa3cf7d4068d76e6de1ccc0f586c7ac9035 | 878 | # Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF 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 File.dirname(__FILE__) + '/spec_helper'
describe Kafka do
before(:each) do
end
end
| 41.809524 | 74 | 0.771071 |
ffc28ff527ee7861685294e9ec41a2dc07e631cb | 171 | class Article < ApplicationRecord
has_many :comments, dependent: :destroy
validates :title, presence: true, length: {minimum: 3}
validates :text, presence: true
end
| 28.5 | 56 | 0.754386 |
e86a95f285ef581961c8bb3fc1311f80294042f2 | 914 | class UserController < ApplicationController
get '/signup' do
erb :"users/signup"
end
post '/signup' do
user = User.new(params)
if user.save
session[:user_id] = user.id
redirect to('/users')
else
flash[:message] = user.errors.full_messages.to_sentence
redirect to('/signup')
end
end
get '/users' do
redirect_if_not_logged_in
erb :"/users/index", :layout => :manage
end
get '/login' do
erb :"users/login"
end
post '/login' do
user = User.find_by(email: params[:email])
if user && user.authenticate(params[:password])
session[:user_id] = user.id
redirect to('/users')
else
flash[:message] = "Invalid email or Password. Please Try Again"
redirect to('/login')
end
end
get '/logout' do
session.destroy
flash[:message] = "Successfully logged out"
redirect to('/')
end
end
| 19.446809 | 69 | 0.615974 |
ab0c3039356a35afce2eecf8fe378917f9c1493a | 3,566 | ##
# This code was generated by
# \ / _ _ _| _ _
# | (_)\/(_)(_|\/| |(/_ v1.0.0
# / /
require 'spec_helper.rb'
describe 'UserChannel' do
it "can read" do
@holodeck.mock(Twilio::Response.new(500, ''))
expect {
@client.ip_messaging.v2.services('ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa') \
.users('USaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa') \
.user_channels.list()
}.to raise_exception(Twilio::REST::TwilioError)
values = {}
expect(
@holodeck.has_request?(Holodeck::Request.new(
method: 'get',
url: 'https://ip-messaging.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Users/USaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels',
))).to eq(true)
end
it "receives read_full responses" do
@holodeck.mock(Twilio::Response.new(
200,
%q[
{
"meta": {
"page": 0,
"page_size": 50,
"first_page_url": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Users/USaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels?PageSize=50&Page=0",
"previous_page_url": null,
"url": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Users/USaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels?PageSize=50&Page=0",
"next_page_url": null,
"key": "channels"
},
"channels": [
{
"account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
"service_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
"channel_sid": "CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
"member_sid": "MBaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
"status": "joined",
"last_consumed_message_index": 5,
"unread_messages_count": 5,
"links": {
"channel": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
"member": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Members/MBaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
}
}
]
}
]
))
actual = @client.ip_messaging.v2.services('ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa') \
.users('USaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa') \
.user_channels.list()
expect(actual).to_not eq(nil)
end
it "receives read_empty responses" do
@holodeck.mock(Twilio::Response.new(
200,
%q[
{
"meta": {
"page": 0,
"page_size": 50,
"first_page_url": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Users/USaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels?PageSize=50&Page=0",
"previous_page_url": null,
"url": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Users/USaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels?PageSize=50&Page=0",
"next_page_url": null,
"key": "channels"
},
"channels": []
}
]
))
actual = @client.ip_messaging.v2.services('ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa') \
.users('USaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa') \
.user_channels.list()
expect(actual).to_not eq(nil)
end
end | 38.76087 | 191 | 0.586371 |
bf43e1c432c535ea5ef60d5edbc319aad2a815b2 | 1,675 | require 'aws-sdk-resources'
module Prpr
module Action
module CodeDeploy
class Deploy < Base
def call
if name = deployment_group_name(event)
deployment = create_deployment(name, deploy_commit)
Prpr::Publisher::Adapter::Base.broadcast message(deployment)
end
end
private
def deploy_commit
event.after
end
def deployment_group_name(event)
if event.ref =~ %r(#{prefix}/(.*))
env.format(:code_deploy_group, { branch: $1 })
else
nil
end
end
def aws
@aws ||= ::Aws::CodeDeploy::Client.new(
region: env[:code_deploy_region] || 'ap-northeast-1',
access_key_id: env[:code_deploy_aws_key],
secret_access_key: env[:code_deploy_aws_secret],
)
end
def create_deployment(deployment_group_name, commit_id)
aws.create_deployment({
application_name: env[:code_deploy_application_name],
deployment_group_name: deployment_group_name,
revision: {
revision_type: "GitHub",
git_hub_location: {
repository: env[:code_deploy_repository],
commit_id: commit_id
}
}
})
end
def message(deployment)
Prpr::Publisher::Message.new(
body: deployment.deployment_id,
from: { login: 'aws' },
room: env[:code_deploy_room])
end
def prefix
env[:code_deploy_prefix] || 'deployment'
end
end
end
end
end
| 26.171875 | 72 | 0.545075 |
f7f39f485e29f23d83ab8c06e4666335d39ab838 | 240 | module Ebay # :nodoc:
module Types # :nodoc:
class VeROReportPacketStatusCode
extend Enumerable
extend Enumeration
Received = 'Received'
InProcess = 'InProcess'
Processed = 'Processed'
end
end
end
| 18.461538 | 36 | 0.65 |
ed44bdd00f7e6f97fb8c2c8d6e965518e4353d13 | 8,129 | Rails.application.routes.draw do
if Rails.env.development?
mount GraphiQL::Rails::Engine, at: "/graphiql", graphql_path: "/graphql"
end
post "/graphql", to: "graphql#execute"
devise_for :users, only: %i[sessions omniauth_callbacks], controllers: { sessions: 'users/sessions', omniauth_callbacks: 'users/omniauth_callbacks' }
devise_scope :user do
post 'users/send_login_email', controller: 'users/sessions', action: 'send_login_email', as: 'user_send_login_email'
post 'users/send_reset_password_email', controller: 'users/sessions', action: 'send_reset_password_email', as: 'user_send_reset_password_email'
get 'users/token', controller: 'users/sessions', action: 'token', as: 'user_token'
get 'users/reset_password', controller: 'users/sessions', action: 'reset_password', as: 'reset_password'
post 'users/update_password', controller: 'users/sessions', action: 'update_password', as: 'update_password'
if Rails.env.development?
get 'users/auth/developer', controller: 'users/omniauth_callbacks', action: 'passthru', as: 'user_developer_omniauth_authorize'
post 'users/auth/developer/callback', controller: 'users/omniauth_callbacks', action: 'developer'
end
end
post 'users/email_bounce', controller: 'users/postmark_webhook', action: 'email_bounce'
authenticate :user, ->(u) { AdminUser.where(email: u.email).present? } do
mount Delayed::Web::Engine, at: '/jobs'
end
mount LetterOpenerWeb::Engine, at: '/letter_opener' if Rails.env.development?
ActiveAdmin.routes(self)
resource :applicants, only: [] do
get '/:token', action: 'enroll' # TODO: Legacy route - remove after a few weeks.
get '/:token/enroll', action: 'enroll', as: "enroll"
end
# TODO: Remove these founder routes as we no longer have 'founders'. Always use the corresponding 'student' routes below.
resource :school, only: %i[show update] do
get 'customize'
get 'admins'
post 'images'
end
namespace :school, module: 'schools' do
resources :faculty, only: %i[create update destroy], as: 'coaches', path: 'coaches' do
collection do
get '/', action: 'school_index'
end
end
resources :targets, only: [] do
resource :content_block, only: %i[create]
end
resources :courses, only: %i[index] do
member do
get 'curriculum'
get 'exports'
get 'authors'
get 'evaluation_criteria'
post 'attach_images'
end
resources :authors, only: %w[show new]
resources :targets, only: [] do
member do
get 'content'
get 'details'
get 'versions'
end
end
resources :levels, only: %i[create]
resources :faculty, as: 'coaches', path: 'coaches', only: [] do
collection do
get '/', action: 'course_index'
end
end
post 'students', action: 'create_students'
post 'mark_teams_active'
get 'students'
get 'inactive_students'
post 'delete_coach_enrollment'
post 'update_coach_enrollments'
end
resources :founders, as: 'students', path: 'students', except: %i[index] do
collection do
post 'team_up'
end
end
resources :levels, only: %i[update] do
resources :target_groups, only: %i[create]
end
resources :target_groups, only: %i[update]
resources :communities, only: %i[index]
end
resources :communities, only: %i[show] do
member do
get 'new_question'
end
end
get 'answers/:id/versions', controller: "answers", action: "versions", as: "answer_version"
get 'questions/:id(/:title)/versions', controller: "questions", action: "versions"
get 'questions/:id(/:title)', controller: "questions", action: "show", as: "question"
get 'home', controller: "users", action: "home", as: "home"
resource :user, only: %i[edit update]
resources :timeline_event_files, only: %i[create] do
member do
get 'download'
end
end
resources :faculty, only: %i[index show] do
post 'connect', on: :member
# get 'dashboard', to: 'faculty/dashboard#index'
collection do
get 'filter/:active_tab', to: 'faculty#index'
get 'weekly_slots/:token', to: 'faculty#weekly_slots', as: 'weekly_slots'
post 'save_weekly_slots/:token', to: 'faculty#save_weekly_slots', as: 'save_weekly_slots'
delete 'weekly_slots/:token', to: 'faculty#mark_unavailable', as: 'mark_unavailable'
get 'slots_saved/:token', to: 'faculty#slots_saved', as: 'slots_saved'
end
# scope module: 'faculty', controller: 'dashboard' do
# get '/', action: 'index'
# end
end
# TODO: Remove these faculty routes as we no longer have 'faculty'. Always use the corresponding 'coaches' routes below.
scope 'coaches', controller: 'faculty' do
get '/', action: 'index', as: 'coaches_index'
get '/:id(/:slug)', action: 'show', as: 'coach'
get '/filter/:active_tab', action: 'index'
end
scope 'library', controller: 'resources' do
get '/', action: 'index', as: 'resources'
get '/:id', action: 'show', as: 'resource'
get '/:id/download', action: 'download', as: 'download_resource'
end
get 'resources/:id', to: redirect('/library/%{id}')
scope 'connect_request', controller: 'connect_request', as: 'connect_request' do
get ':id/feedback/from_team/:token', action: 'feedback_from_team', as: 'feedback_from_team'
get ':id/feedback/from_faculty/:token', action: 'feedback_from_faculty', as: 'feedback_from_faculty'
get ':id/join_session(/:token)', action: 'join_session', as: 'join_session'
patch ':id/feedback/comment/:token', action: 'comment_submit', as: 'comment_submit'
end
resources :prospective_applicants, only: %i[create]
resources :colleges, only: :index
resource :platform_feedback, only: %i[create]
# Founder show
scope 'students', controller: 'founders' do
get '/:id/report', action: 'report', as: 'student_report'
get '/:id(/:slug)', action: 'show', as: 'student'
get '/:id/events/:page', action: 'paged_events', as: 'paged_events'
get '/:id/e/:event_id(/:event_title)', action: 'timeline_event_show', as: 'student_timeline_event_show'
end
get 'styleguide', to: 'home#styleguide', constraints: DevelopmentConstraint.new
root 'home#index'
get 'agreements/:agreement_type', as: 'agreement', controller: 'home', action: 'agreement'
# TODO: Remove the backwards-compatibility paths after a while.
get 'policies/privacy', to: redirect('/agreements/privacy-policy')
get 'policies/terms', to: redirect('/agreements/terms-of-use')
resources :targets, only: %i[show] do
member do
get 'details_v2'
get ':slug', action: 'show'
end
end
resources :timeline_events, only: %i[show], path: 'submissions'
resources :courses, only: %i[show] do
member do
get 'review', action: 'review'
get 'students', action: 'students'
get 'leaderboard', action: 'leaderboard'
get 'curriculum', action: 'curriculum'
get 'apply', action: 'apply'
get '/(:name)', action: 'show'
end
end
resources :markdown_attachments, only: %i[create] do
member do
get '/:token', action: 'download', as: 'download'
end
end
resource :impersonation, only: %i[destroy]
scope 'intercom', as: 'intercom', controller: 'intercom' do
post 'user_create', action: 'user_create_webhook'
post 'unsubscribe', action: 'email_unsubscribe_webhook'
end
get '/help/:document', to: 'help#show'
# Handle incoming unsubscribe webhooks from SendInBlue
post '/send_in_blue/unsubscribe', to: 'send_in_blue#unsubscribe_webhook'
# Handle redirects of short URLs.
get 'r/:unique_key', to: 'shortened_urls#redirect', as: 'short_redirect'
get '/oauth/:provider', to: 'home#oauth', as: 'oauth', constraints: SsoConstraint.new
get '/oauth_error', to: 'home#oauth_error', as: 'oauth_error'
# Allow developers to simulate the error pages.
get '/errors/:error_type', to: 'errors#simulate', constraints: DevelopmentConstraint.new
get '/favicon.ico', to: 'home#favicon'
end
| 33.870833 | 151 | 0.670808 |
332d3b6f77e2947b163439df0f7e6aca3540dc87 | 75 | module MyCustomHelper
def quote
quote =[]
quote[0] = ""
end
end | 12.5 | 21 | 0.6 |
f7f45b87921f330a88b6bb65dc8b6dc1e8e63f0e | 35,427 | # frozen_string_literal: true
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# Auto-generated by gapic-generator-ruby. DO NOT EDIT!
require "gapic/operation"
require "google/longrunning/operations_pb"
module Google
module Cloud
module Bigtable
module Admin
module V2
module BigtableInstanceAdmin
# Service that implements Longrunning Operations API.
class Operations
# @private
attr_reader :operations_stub
##
# Configuration for the BigtableInstanceAdmin Operations API.
#
# @yield [config] Configure the Operations client.
# @yieldparam config [Operations::Configuration]
#
# @return [Operations::Configuration]
#
def self.configure
@configure ||= Operations::Configuration.new
yield @configure if block_given?
@configure
end
##
# Configure the BigtableInstanceAdmin Operations instance.
#
# The configuration is set to the derived mode, meaning that values can be changed,
# but structural changes (adding new fields, etc.) are not allowed. Structural changes
# should be made on {Operations.configure}.
#
# @yield [config] Configure the Operations client.
# @yieldparam config [Operations::Configuration]
#
# @return [Operations::Configuration]
#
def configure
yield @config if block_given?
@config
end
##
# Create a new Operations client object.
#
# @yield [config] Configure the Client client.
# @yieldparam config [Operations::Configuration]
#
def initialize
# These require statements are intentionally placed here to initialize
# the gRPC module only when it's required.
# See https://github.com/googleapis/toolkit/issues/446
require "gapic/grpc"
require "google/longrunning/operations_services_pb"
# Create the configuration object
@config = Configuration.new Operations.configure
# Yield the configuration if needed
yield @config if block_given?
# Create credentials
credentials = @config.credentials
credentials ||= Credentials.default scope: @config.scope
if credentials.is_a?(String) || credentials.is_a?(Hash)
credentials = Credentials.new credentials, scope: @config.scope
end
@quota_project_id = @config.quota_project
@quota_project_id ||= credentials.quota_project_id if credentials.respond_to? :quota_project_id
@operations_stub = ::Gapic::ServiceStub.new(
::Google::Longrunning::Operations::Stub,
credentials: credentials,
endpoint: @config.endpoint,
channel_args: @config.channel_args,
interceptors: @config.interceptors
)
end
# Service calls
##
# Lists operations that match the specified filter in the request. If the
# server doesn't support this method, it returns `UNIMPLEMENTED`.
#
# NOTE: the `name` binding allows API services to override the binding
# to use different resource name schemes, such as `users/*/operations`. To
# override the binding, API services can add a binding such as
# `"/v1/{name=users/*}/operations"` to their service configuration.
# For backwards compatibility, the default name includes the operations
# collection id, however overriding users must ensure the name binding
# is the parent resource, without the operations collection id.
#
# @overload list_operations(request, options = nil)
# Pass arguments to `list_operations` via a request object, either of type
# {::Google::Longrunning::ListOperationsRequest} or an equivalent Hash.
#
# @param request [::Google::Longrunning::ListOperationsRequest, ::Hash]
# A request object representing the call parameters. Required. To specify no
# parameters, or to keep all the default parameter values, pass an empty Hash.
# @param options [::Gapic::CallOptions, ::Hash]
# Overrides the default settings for this call, e.g, timeout, retries, etc. Optional.
#
# @overload list_operations(name: nil, filter: nil, page_size: nil, page_token: nil)
# Pass arguments to `list_operations` via keyword arguments. Note that at
# least one keyword argument is required. To specify no parameters, or to keep all
# the default parameter values, pass an empty Hash as a request object (see above).
#
# @param name [::String]
# The name of the operation's parent resource.
# @param filter [::String]
# The standard list filter.
# @param page_size [::Integer]
# The standard list page size.
# @param page_token [::String]
# The standard list page token.
#
# @yield [response, operation] Access the result along with the RPC operation
# @yieldparam response [::Gapic::PagedEnumerable<::Gapic::Operation>]
# @yieldparam operation [::GRPC::ActiveCall::Operation]
#
# @return [::Gapic::PagedEnumerable<::Gapic::Operation>]
#
# @raise [::Google::Cloud::Error] if the RPC is aborted.
#
def list_operations request, options = nil
raise ::ArgumentError, "request must be provided" if request.nil?
request = ::Gapic::Protobuf.coerce request, to: ::Google::Longrunning::ListOperationsRequest
# Converts hash and nil to an options object
options = ::Gapic::CallOptions.new(**options.to_h) if options.respond_to? :to_h
# Customize the options with defaults
metadata = @config.rpcs.list_operations.metadata.to_h
# Set x-goog-api-client and x-goog-user-project headers
metadata[:"x-goog-api-client"] ||= ::Gapic::Headers.x_goog_api_client \
lib_name: @config.lib_name, lib_version: @config.lib_version,
gapic_version: ::Google::Cloud::Bigtable::Admin::V2::VERSION
metadata[:"x-goog-user-project"] = @quota_project_id if @quota_project_id
header_params = {
"name" => request.name
}
request_params_header = header_params.map { |k, v| "#{k}=#{v}" }.join("&")
metadata[:"x-goog-request-params"] ||= request_params_header
options.apply_defaults timeout: @config.rpcs.list_operations.timeout,
metadata: metadata,
retry_policy: @config.rpcs.list_operations.retry_policy
options.apply_defaults metadata: @config.metadata,
retry_policy: @config.retry_policy
@operations_stub.call_rpc :list_operations, request, options: options do |response, operation|
wrap_lro_operation = ->(op_response) { ::Gapic::Operation.new op_response, @operations_client }
response = ::Gapic::PagedEnumerable.new @operations_stub, :list_operations, request, response, operation, options, format_resource: wrap_lro_operation
yield response, operation if block_given?
return response
end
rescue ::GRPC::BadStatus => e
raise ::Google::Cloud::Error.from_error(e)
end
##
# Gets the latest state of a long-running operation. Clients can use this
# method to poll the operation result at intervals as recommended by the API
# service.
#
# @overload get_operation(request, options = nil)
# Pass arguments to `get_operation` via a request object, either of type
# {::Google::Longrunning::GetOperationRequest} or an equivalent Hash.
#
# @param request [::Google::Longrunning::GetOperationRequest, ::Hash]
# A request object representing the call parameters. Required. To specify no
# parameters, or to keep all the default parameter values, pass an empty Hash.
# @param options [::Gapic::CallOptions, ::Hash]
# Overrides the default settings for this call, e.g, timeout, retries, etc. Optional.
#
# @overload get_operation(name: nil)
# Pass arguments to `get_operation` via keyword arguments. Note that at
# least one keyword argument is required. To specify no parameters, or to keep all
# the default parameter values, pass an empty Hash as a request object (see above).
#
# @param name [::String]
# The name of the operation resource.
#
# @yield [response, operation] Access the result along with the RPC operation
# @yieldparam response [::Gapic::Operation]
# @yieldparam operation [::GRPC::ActiveCall::Operation]
#
# @return [::Gapic::Operation]
#
# @raise [::Google::Cloud::Error] if the RPC is aborted.
#
def get_operation request, options = nil
raise ::ArgumentError, "request must be provided" if request.nil?
request = ::Gapic::Protobuf.coerce request, to: ::Google::Longrunning::GetOperationRequest
# Converts hash and nil to an options object
options = ::Gapic::CallOptions.new(**options.to_h) if options.respond_to? :to_h
# Customize the options with defaults
metadata = @config.rpcs.get_operation.metadata.to_h
# Set x-goog-api-client and x-goog-user-project headers
metadata[:"x-goog-api-client"] ||= ::Gapic::Headers.x_goog_api_client \
lib_name: @config.lib_name, lib_version: @config.lib_version,
gapic_version: ::Google::Cloud::Bigtable::Admin::V2::VERSION
metadata[:"x-goog-user-project"] = @quota_project_id if @quota_project_id
header_params = {
"name" => request.name
}
request_params_header = header_params.map { |k, v| "#{k}=#{v}" }.join("&")
metadata[:"x-goog-request-params"] ||= request_params_header
options.apply_defaults timeout: @config.rpcs.get_operation.timeout,
metadata: metadata,
retry_policy: @config.rpcs.get_operation.retry_policy
options.apply_defaults metadata: @config.metadata,
retry_policy: @config.retry_policy
@operations_stub.call_rpc :get_operation, request, options: options do |response, operation|
response = ::Gapic::Operation.new response, @operations_client, options: options
yield response, operation if block_given?
return response
end
rescue ::GRPC::BadStatus => e
raise ::Google::Cloud::Error.from_error(e)
end
##
# Deletes a long-running operation. This method indicates that the client is
# no longer interested in the operation result. It does not cancel the
# operation. If the server doesn't support this method, it returns
# `google.rpc.Code.UNIMPLEMENTED`.
#
# @overload delete_operation(request, options = nil)
# Pass arguments to `delete_operation` via a request object, either of type
# {::Google::Longrunning::DeleteOperationRequest} or an equivalent Hash.
#
# @param request [::Google::Longrunning::DeleteOperationRequest, ::Hash]
# A request object representing the call parameters. Required. To specify no
# parameters, or to keep all the default parameter values, pass an empty Hash.
# @param options [::Gapic::CallOptions, ::Hash]
# Overrides the default settings for this call, e.g, timeout, retries, etc. Optional.
#
# @overload delete_operation(name: nil)
# Pass arguments to `delete_operation` via keyword arguments. Note that at
# least one keyword argument is required. To specify no parameters, or to keep all
# the default parameter values, pass an empty Hash as a request object (see above).
#
# @param name [::String]
# The name of the operation resource to be deleted.
#
# @yield [response, operation] Access the result along with the RPC operation
# @yieldparam response [::Google::Protobuf::Empty]
# @yieldparam operation [::GRPC::ActiveCall::Operation]
#
# @return [::Google::Protobuf::Empty]
#
# @raise [::Google::Cloud::Error] if the RPC is aborted.
#
def delete_operation request, options = nil
raise ::ArgumentError, "request must be provided" if request.nil?
request = ::Gapic::Protobuf.coerce request, to: ::Google::Longrunning::DeleteOperationRequest
# Converts hash and nil to an options object
options = ::Gapic::CallOptions.new(**options.to_h) if options.respond_to? :to_h
# Customize the options with defaults
metadata = @config.rpcs.delete_operation.metadata.to_h
# Set x-goog-api-client and x-goog-user-project headers
metadata[:"x-goog-api-client"] ||= ::Gapic::Headers.x_goog_api_client \
lib_name: @config.lib_name, lib_version: @config.lib_version,
gapic_version: ::Google::Cloud::Bigtable::Admin::V2::VERSION
metadata[:"x-goog-user-project"] = @quota_project_id if @quota_project_id
header_params = {
"name" => request.name
}
request_params_header = header_params.map { |k, v| "#{k}=#{v}" }.join("&")
metadata[:"x-goog-request-params"] ||= request_params_header
options.apply_defaults timeout: @config.rpcs.delete_operation.timeout,
metadata: metadata,
retry_policy: @config.rpcs.delete_operation.retry_policy
options.apply_defaults metadata: @config.metadata,
retry_policy: @config.retry_policy
@operations_stub.call_rpc :delete_operation, request, options: options do |response, operation|
yield response, operation if block_given?
return response
end
rescue ::GRPC::BadStatus => e
raise ::Google::Cloud::Error.from_error(e)
end
##
# Starts asynchronous cancellation on a long-running operation. The server
# makes a best effort to cancel the operation, but success is not
# guaranteed. If the server doesn't support this method, it returns
# `google.rpc.Code.UNIMPLEMENTED`. Clients can use
# Operations.GetOperation or
# other methods to check whether the cancellation succeeded or whether the
# operation completed despite cancellation. On successful cancellation,
# the operation is not deleted; instead, it becomes an operation with
# an {::Google::Longrunning::Operation#error Operation.error} value with a {::Google::Rpc::Status#code google.rpc.Status.code} of 1,
# corresponding to `Code.CANCELLED`.
#
# @overload cancel_operation(request, options = nil)
# Pass arguments to `cancel_operation` via a request object, either of type
# {::Google::Longrunning::CancelOperationRequest} or an equivalent Hash.
#
# @param request [::Google::Longrunning::CancelOperationRequest, ::Hash]
# A request object representing the call parameters. Required. To specify no
# parameters, or to keep all the default parameter values, pass an empty Hash.
# @param options [::Gapic::CallOptions, ::Hash]
# Overrides the default settings for this call, e.g, timeout, retries, etc. Optional.
#
# @overload cancel_operation(name: nil)
# Pass arguments to `cancel_operation` via keyword arguments. Note that at
# least one keyword argument is required. To specify no parameters, or to keep all
# the default parameter values, pass an empty Hash as a request object (see above).
#
# @param name [::String]
# The name of the operation resource to be cancelled.
#
# @yield [response, operation] Access the result along with the RPC operation
# @yieldparam response [::Google::Protobuf::Empty]
# @yieldparam operation [::GRPC::ActiveCall::Operation]
#
# @return [::Google::Protobuf::Empty]
#
# @raise [::Google::Cloud::Error] if the RPC is aborted.
#
def cancel_operation request, options = nil
raise ::ArgumentError, "request must be provided" if request.nil?
request = ::Gapic::Protobuf.coerce request, to: ::Google::Longrunning::CancelOperationRequest
# Converts hash and nil to an options object
options = ::Gapic::CallOptions.new(**options.to_h) if options.respond_to? :to_h
# Customize the options with defaults
metadata = @config.rpcs.cancel_operation.metadata.to_h
# Set x-goog-api-client and x-goog-user-project headers
metadata[:"x-goog-api-client"] ||= ::Gapic::Headers.x_goog_api_client \
lib_name: @config.lib_name, lib_version: @config.lib_version,
gapic_version: ::Google::Cloud::Bigtable::Admin::V2::VERSION
metadata[:"x-goog-user-project"] = @quota_project_id if @quota_project_id
header_params = {
"name" => request.name
}
request_params_header = header_params.map { |k, v| "#{k}=#{v}" }.join("&")
metadata[:"x-goog-request-params"] ||= request_params_header
options.apply_defaults timeout: @config.rpcs.cancel_operation.timeout,
metadata: metadata,
retry_policy: @config.rpcs.cancel_operation.retry_policy
options.apply_defaults metadata: @config.metadata,
retry_policy: @config.retry_policy
@operations_stub.call_rpc :cancel_operation, request, options: options do |response, operation|
yield response, operation if block_given?
return response
end
rescue ::GRPC::BadStatus => e
raise ::Google::Cloud::Error.from_error(e)
end
##
# Waits for the specified long-running operation until it is done or reaches
# at most a specified timeout, returning the latest state. If the operation
# is already done, the latest state is immediately returned. If the timeout
# specified is greater than the default HTTP/RPC timeout, the HTTP/RPC
# timeout is used. If the server does not support this method, it returns
# `google.rpc.Code.UNIMPLEMENTED`.
# Note that this method is on a best-effort basis. It may return the latest
# state before the specified timeout (including immediately), meaning even an
# immediate response is no guarantee that the operation is done.
#
# @overload wait_operation(request, options = nil)
# Pass arguments to `wait_operation` via a request object, either of type
# {::Google::Longrunning::WaitOperationRequest} or an equivalent Hash.
#
# @param request [::Google::Longrunning::WaitOperationRequest, ::Hash]
# A request object representing the call parameters. Required. To specify no
# parameters, or to keep all the default parameter values, pass an empty Hash.
# @param options [::Gapic::CallOptions, ::Hash]
# Overrides the default settings for this call, e.g, timeout, retries, etc. Optional.
#
# @overload wait_operation(name: nil, timeout: nil)
# Pass arguments to `wait_operation` via keyword arguments. Note that at
# least one keyword argument is required. To specify no parameters, or to keep all
# the default parameter values, pass an empty Hash as a request object (see above).
#
# @param name [::String]
# The name of the operation resource to wait on.
# @param timeout [::Google::Protobuf::Duration, ::Hash]
# The maximum duration to wait before timing out. If left blank, the wait
# will be at most the time permitted by the underlying HTTP/RPC protocol.
# If RPC context deadline is also specified, the shorter one will be used.
#
# @yield [response, operation] Access the result along with the RPC operation
# @yieldparam response [::Gapic::Operation]
# @yieldparam operation [::GRPC::ActiveCall::Operation]
#
# @return [::Gapic::Operation]
#
# @raise [::Google::Cloud::Error] if the RPC is aborted.
#
def wait_operation request, options = nil
raise ::ArgumentError, "request must be provided" if request.nil?
request = ::Gapic::Protobuf.coerce request, to: ::Google::Longrunning::WaitOperationRequest
# Converts hash and nil to an options object
options = ::Gapic::CallOptions.new(**options.to_h) if options.respond_to? :to_h
# Customize the options with defaults
metadata = @config.rpcs.wait_operation.metadata.to_h
# Set x-goog-api-client and x-goog-user-project headers
metadata[:"x-goog-api-client"] ||= ::Gapic::Headers.x_goog_api_client \
lib_name: @config.lib_name, lib_version: @config.lib_version,
gapic_version: ::Google::Cloud::Bigtable::Admin::V2::VERSION
metadata[:"x-goog-user-project"] = @quota_project_id if @quota_project_id
options.apply_defaults timeout: @config.rpcs.wait_operation.timeout,
metadata: metadata,
retry_policy: @config.rpcs.wait_operation.retry_policy
options.apply_defaults metadata: @config.metadata,
retry_policy: @config.retry_policy
@operations_stub.call_rpc :wait_operation, request, options: options do |response, operation|
response = ::Gapic::Operation.new response, @operations_client, options: options
yield response, operation if block_given?
return response
end
rescue ::GRPC::BadStatus => e
raise ::Google::Cloud::Error.from_error(e)
end
##
# Configuration class for the Operations API.
#
# This class represents the configuration for Operations,
# providing control over timeouts, retry behavior, logging, transport
# parameters, and other low-level controls. Certain parameters can also be
# applied individually to specific RPCs. See
# {::Google::Longrunning::Operations::Client::Configuration::Rpcs}
# for a list of RPCs that can be configured independently.
#
# Configuration can be applied globally to all clients, or to a single client
# on construction.
#
# # Examples
#
# To modify the global config, setting the timeout for list_operations
# to 20 seconds, and all remaining timeouts to 10 seconds:
#
# ::Google::Longrunning::Operations::Client.configure do |config|
# config.timeout = 10.0
# config.rpcs.list_operations.timeout = 20.0
# end
#
# To apply the above configuration only to a new client:
#
# client = ::Google::Longrunning::Operations::Client.new do |config|
# config.timeout = 10.0
# config.rpcs.list_operations.timeout = 20.0
# end
#
# @!attribute [rw] endpoint
# The hostname or hostname:port of the service endpoint.
# Defaults to `"bigtableadmin.googleapis.com"`.
# @return [::String]
# @!attribute [rw] credentials
# Credentials to send with calls. You may provide any of the following types:
# * (`String`) The path to a service account key file in JSON format
# * (`Hash`) A service account key as a Hash
# * (`Google::Auth::Credentials`) A googleauth credentials object
# (see the [googleauth docs](https://googleapis.dev/ruby/googleauth/latest/index.html))
# * (`Signet::OAuth2::Client`) A signet oauth2 client object
# (see the [signet docs](https://googleapis.dev/ruby/signet/latest/Signet/OAuth2/Client.html))
# * (`GRPC::Core::Channel`) a gRPC channel with included credentials
# * (`GRPC::Core::ChannelCredentials`) a gRPC credentails object
# * (`nil`) indicating no credentials
# @return [::Object]
# @!attribute [rw] scope
# The OAuth scopes
# @return [::Array<::String>]
# @!attribute [rw] lib_name
# The library name as recorded in instrumentation and logging
# @return [::String]
# @!attribute [rw] lib_version
# The library version as recorded in instrumentation and logging
# @return [::String]
# @!attribute [rw] channel_args
# Extra parameters passed to the gRPC channel. Note: this is ignored if a
# `GRPC::Core::Channel` object is provided as the credential.
# @return [::Hash]
# @!attribute [rw] interceptors
# An array of interceptors that are run before calls are executed.
# @return [::Array<::GRPC::ClientInterceptor>]
# @!attribute [rw] timeout
# The call timeout in seconds.
# @return [::Numeric]
# @!attribute [rw] metadata
# Additional gRPC headers to be sent with the call.
# @return [::Hash{::Symbol=>::String}]
# @!attribute [rw] retry_policy
# The retry policy. The value is a hash with the following keys:
# * `:initial_delay` (*type:* `Numeric`) - The initial delay in seconds.
# * `:max_delay` (*type:* `Numeric`) - The max delay in seconds.
# * `:multiplier` (*type:* `Numeric`) - The incremental backoff multiplier.
# * `:retry_codes` (*type:* `Array<String>`) - The error codes that should
# trigger a retry.
# @return [::Hash]
# @!attribute [rw] quota_project
# A separate project against which to charge quota.
# @return [::String]
#
class Configuration
extend ::Gapic::Config
config_attr :endpoint, "bigtableadmin.googleapis.com", ::String
config_attr :credentials, nil do |value|
allowed = [::String, ::Hash, ::Proc, ::Symbol, ::Google::Auth::Credentials, ::Signet::OAuth2::Client, nil]
allowed += [::GRPC::Core::Channel, ::GRPC::Core::ChannelCredentials] if defined? ::GRPC
allowed.any? { |klass| klass === value }
end
config_attr :scope, nil, ::String, ::Array, nil
config_attr :lib_name, nil, ::String, nil
config_attr :lib_version, nil, ::String, nil
config_attr(:channel_args, { "grpc.service_config_disable_resolution" => 1 }, ::Hash, nil)
config_attr :interceptors, nil, ::Array, nil
config_attr :timeout, nil, ::Numeric, nil
config_attr :metadata, nil, ::Hash, nil
config_attr :retry_policy, nil, ::Hash, ::Proc, nil
config_attr :quota_project, nil, ::String, nil
# @private
def initialize parent_config = nil
@parent_config = parent_config unless parent_config.nil?
yield self if block_given?
end
##
# Configurations for individual RPCs
# @return [Rpcs]
#
def rpcs
@rpcs ||= begin
parent_rpcs = nil
parent_rpcs = @parent_config.rpcs if defined?(@parent_config) && @parent_config.respond_to?(:rpcs)
Rpcs.new parent_rpcs
end
end
##
# Configuration RPC class for the Operations API.
#
# Includes fields providing the configuration for each RPC in this service.
# Each configuration object is of type `Gapic::Config::Method` and includes
# the following configuration fields:
#
# * `timeout` (*type:* `Numeric`) - The call timeout in seconds
# * `metadata` (*type:* `Hash{Symbol=>String}`) - Additional gRPC headers
# * `retry_policy (*type:* `Hash`) - The retry policy. The policy fields
# include the following keys:
# * `:initial_delay` (*type:* `Numeric`) - The initial delay in seconds.
# * `:max_delay` (*type:* `Numeric`) - The max delay in seconds.
# * `:multiplier` (*type:* `Numeric`) - The incremental backoff multiplier.
# * `:retry_codes` (*type:* `Array<String>`) - The error codes that should
# trigger a retry.
#
class Rpcs
##
# RPC-specific configuration for `list_operations`
# @return [::Gapic::Config::Method]
#
attr_reader :list_operations
##
# RPC-specific configuration for `get_operation`
# @return [::Gapic::Config::Method]
#
attr_reader :get_operation
##
# RPC-specific configuration for `delete_operation`
# @return [::Gapic::Config::Method]
#
attr_reader :delete_operation
##
# RPC-specific configuration for `cancel_operation`
# @return [::Gapic::Config::Method]
#
attr_reader :cancel_operation
##
# RPC-specific configuration for `wait_operation`
# @return [::Gapic::Config::Method]
#
attr_reader :wait_operation
# @private
def initialize parent_rpcs = nil
list_operations_config = parent_rpcs.list_operations if parent_rpcs.respond_to? :list_operations
@list_operations = ::Gapic::Config::Method.new list_operations_config
get_operation_config = parent_rpcs.get_operation if parent_rpcs.respond_to? :get_operation
@get_operation = ::Gapic::Config::Method.new get_operation_config
delete_operation_config = parent_rpcs.delete_operation if parent_rpcs.respond_to? :delete_operation
@delete_operation = ::Gapic::Config::Method.new delete_operation_config
cancel_operation_config = parent_rpcs.cancel_operation if parent_rpcs.respond_to? :cancel_operation
@cancel_operation = ::Gapic::Config::Method.new cancel_operation_config
wait_operation_config = parent_rpcs.wait_operation if parent_rpcs.respond_to? :wait_operation
@wait_operation = ::Gapic::Config::Method.new wait_operation_config
yield self if block_given?
end
end
end
end
end
end
end
end
end
end
| 53.840426 | 168 | 0.556017 |
bb074195f9aef751f361747ba0bd06efa8dc7cfe | 285 | class AddIndicesToMemberships < ActiveRecord::Migration
self.disable_ddl_transaction!
def up
execute "CREATE INDEX CONCURRENTLY index_memberships_on_user_id ON memberships(user_id)"
end
def down
execute "DROP INDEX CONCURRENTLY index_memberships_on_user_id"
end
end | 25.909091 | 92 | 0.810526 |
1d8923f4552e7b9abc3db25c08f620a9bd7343df | 263 | require 'uri'
module Mondo
module Utils
extend self
# String Helpers
def camelize(str)
str.split('_').map(&:capitalize).join
end
def underscore(str)
str.gsub(/(.)([A-Z])/) { "#{$1}_#{$2.downcase}" }.downcase
end
end
end
| 15.470588 | 64 | 0.574144 |
01bba50a18fbc97e74145d02b698c3b8e3776623 | 1,223 | Pod::Spec.new do |s|
s.name = "BraintreeVisaCheckout"
s.version = "6.0.0"
s.summary = "Braintree Visa Checkout component for use with the Braintree iOS SDK"
s.description = <<-DESC
Braintree is a full-stack payments platform for developers
This CocoaPod will help you accept Visa Checkout payments in your iOS app.
Check out our development portal at https://developers.braintreepayments.com.
DESC
s.homepage = "https://www.braintreepayments.com/how-braintree-works"
s.documentation_url = "https://developers.braintreepayments.com/guides/visa-checkout/overview"
s.license = "MIT"
s.author = { "Braintree" => "[email protected]" }
s.source = { :git => "https://github.com/braintree/braintree-ios-visa-checkout.git", :tag => s.version.to_s }
s.platform = :ios, "12.0"
s.compiler_flags = "-Wall -Werror -Wextra"
s.source_files = "BraintreeVisaCheckout/**/*.{h,m}"
s.public_header_files = "BraintreeVisaCheckout/Public/**/*.h"
s.vendored_frameworks = "Frameworks/VisaCheckoutSDK.xcframework"
s.dependency "Braintree/Core", "~> 5.0"
end
| 45.296296 | 121 | 0.638594 |
e9ac18c5f6ad7bb2915debaf654dddfe9374d3a2 | 147 | # Be sure to restart your server when you modify this file.
PoweredBy::Application.config.session_store :cookie_store, key: '_powered-by_session'
| 36.75 | 85 | 0.802721 |
33a3bc4a311b529fd8e8b1b0d7ea1e98eba8b629 | 2,734 | # Authentication wrapper around other Totem::Settings.
module Totem
module Core
module Support
class Authentication
attr_reader :totem_settings
# Should always use the public methods to access these instance variables.
# Listing the instance variables used to provide easily access if needed.
attr_reader :platform_authentication_settings
def initialize(env)
@totem_settings = env
@platform_authentication_settings = ActiveSupport::OrderedOptions.new
end
# define authentication.
def authentication; self; end
def platforms; platform_authentication_settings; end
def platform(platform_name)
error "Platform [#{platform_name.inspect}] is blank" if platform_name.blank?
platforms[platform_name]
end
def set_platform(platform_name, settings)
error "Platform [#{platform_name}] is blank in set platform" if platform_name.blank?
@platform_authentication_settings[platform_name] = settings
end
def model_class(platform_name, class_name=:user_model)
platform(platform_name) && platform(platform_name).classes.get_class(class_name)
end
def current_model_class(object, class_name=:user_model); model_class(get_platform_name(object), class_name); end
# ### Routes Section
def route(platform_name, key); get_platform_name_value(platform_name, :routes, key); end
def current_route(object, key); route(get_platform_name(object), key); end
def current_home_route(object); current_route(object, :home); end
# ### Session Section
def session(platform_name); get_platform_name_value(platform_name, :session); end
def current_session(object); session(get_platform_name(object)); end
def session_timeout(platform_name); get_platform_name_value(platform_name, :session, :timeout_time); end
def current_session_timeout(object); session_timeout(get_platform_name(object)); end
def session_expire_after(platform_name); get_platform_name_value(platform_name, :session, :expire_after_time); end
def current_session_expire_after(object); session_expire_after(get_platform_name(object)); end
private
def get_platform_name(object); totem_settings.engine.current_platform_name(object); end
def get_platform_name_value(*args)
platform_name = args.shift
value = platform(platform_name)
args.each do |arg|
value = value[arg]
break if value.blank?
end
value
end
include Shared
end
end
end
end | 34.175 | 122 | 0.68654 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.