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
|
---|---|---|---|---|---|
33f7e78bf7bad4c3f173b192a565d02b4a13e5d2 | 4,302 | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'Query.vulnerabilities.externalIssueLinks' do
include GraphqlHelpers
include ReactiveCachingHelpers
let_it_be(:project) { create(:project) }
let_it_be(:jira_integration) { create(:jira_integration, project: project, issues_enabled: true, project_key: 'GV') }
let_it_be(:user) { create(:user, security_dashboard_projects: [project]) }
let_it_be(:vulnerability) { create(:vulnerability, project: project) }
let_it_be(:vulnerability_external_issue_link) { create(:vulnerabilities_external_issue_link, external_issue_key: '10001', vulnerability: vulnerability) }
let_it_be(:fields) do
<<~QUERY
externalIssueLinks {
nodes {
id
linkType
externalIssue {
externalTracker
relativeReference
status
title
webUrl
createdAt
updatedAt
}
}
}
QUERY
end
let_it_be(:query) { graphql_query_for('vulnerabilities', {}, query_graphql_field('nodes', {}, fields)) }
before do
project.add_developer(user)
stub_licensed_features(security_dashboard: true, jira_issues_integration: true)
end
context 'when queried for the first time with reactive caching' do
let_it_be(:expected_response) do
[
{
'externalIssueLinks' => {
'nodes' => [
{
'externalIssue' => nil,
'id' => "gid://gitlab/Vulnerabilities::ExternalIssueLink/#{vulnerability_external_issue_link.id}",
'linkType' => 'CREATED'
}
]
}
}
]
end
it 'schedules a background job to fetch data from Jira' do
Sidekiq::Testing.fake! do
expect { post_graphql(query, current_user: user) }.to change(ExternalServiceReactiveCachingWorker.jobs, :size).by(1)
expect(ExternalServiceReactiveCachingWorker.jobs.last['args']).to include(project.id, [vulnerability_external_issue_link.external_issue_key])
end
end
it 'returns null as value for externalIssue' do
post_graphql(query, current_user: user)
expect(graphql_data['vulnerabilities']['nodes']).to eq(expected_response)
end
end
context 'when queried without reactive caching' do
let_it_be(:expected_response) do
[
{
'externalIssueLinks' => {
'nodes' => [
{
'externalIssue' => {
'createdAt' => '2020-12-16T09:42:03Z',
'externalTracker' => 'jira',
'relativeReference' => 'GV-100',
'status' => 'To Do',
'title' => 'Investigate vulnerability: Filesystem function basename() detected with dynamic parameter directly from user input',
'updatedAt' => '2020-12-16T09:42:03Z',
'webUrl' => 'https://jira.example.com/browse/GV-100'
},
'id' => "gid://gitlab/Vulnerabilities::ExternalIssueLink/#{vulnerability_external_issue_link.id}",
'linkType' => 'CREATED'
}
]
}
}
]
end
let_it_be(:jira_issue_response) do
{
total: 1,
issues: [
{
id: '10001',
key: 'GV-100',
fields: {
summary: 'Investigate vulnerability: Filesystem function basename() detected with dynamic parameter directly from user input',
created: '2020-12-16T10:42:03.071+0100',
updated: '2020-12-16T10:42:03.071+0100',
status: {
name: 'To Do'
}
}
}
]
}.to_json
end
before do
stub_request(:get, /.*10001.*/).to_return(status: 200, body: jira_issue_response, headers: { 'Content-Type' => 'application/json;charset=UTF-8' })
allow_next_instance_of(Projects::Integrations::Jira::ByIdsFinder) { |by_ids_finder| synchronous_reactive_cache(by_ids_finder) }
end
it 'returns a list of all VulnerabilityExternalIssueLink', :sidekiq_inline do
post_graphql(query, current_user: user)
expect(graphql_data['vulnerabilities']['nodes']).to eq(expected_response)
end
end
end
| 32.590909 | 155 | 0.595769 |
796fb1ae0c29ff517ea5713997dd4d20d54fc333 | 223 | # TODO: Write here Module presentation
module LatoSwpmanager
# include here external gems
# require 'gem'
# include engine and interface
require 'lato_swpmanager/engine'
require 'lato_swpmanager/interface'
end
| 18.583333 | 38 | 0.766816 |
bb019d5d091f77a9606bcfb26d589c1c219a032b | 306 | class SometimesSecret
include Mongoid::Document
include Mongoid::CachedJson
field :secret, default: 'Afraid of the dark'
field :should_tell_secret, type: Boolean
belongs_to :secret_parent
json_fields hide_as_child_json_when: lambda { |x| !x.should_tell_secret },
secret: {}
end
| 25.5 | 76 | 0.735294 |
ff63307755dc763f7f4dbe0786b4b50b37dc3d6b | 1,413 | # 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 Mailosaur
module Models
#
# Advanced use case content related to the message.
#
class Metadata
# @return [Array<MessageHeader>] Email headers.
attr_accessor :headers
#
# Mapper for Metadata class as Ruby Hash.
# This will be used for serialization/deserialization.
#
def self.mapper()
{
client_side_validation: true,
required: false,
serialized_name: 'Metadata',
type: {
name: 'Composite',
class_name: 'Metadata',
model_properties: {
headers: {
client_side_validation: true,
required: false,
serialized_name: 'headers',
type: {
name: 'Sequence',
element: {
client_side_validation: true,
required: false,
serialized_name: 'MessageHeaderElementType',
type: {
name: 'Composite',
class_name: 'MessageHeader'
}
}
}
}
}
}
}
end
end
end
end
| 26.660377 | 70 | 0.485492 |
18399ccef1af0eb0d8396b5d50b65881267b48c9 | 693 | # -*- encoding: utf-8 -*-
# stub: turbolinks-source 5.2.0 ruby lib
Gem::Specification.new do |s|
s.name = "turbolinks-source".freeze
s.version = "5.2.0"
s.required_rubygems_version = Gem::Requirement.new(">= 0".freeze) if s.respond_to? :required_rubygems_version=
s.require_paths = ["lib".freeze]
s.authors = ["Sam Stephenson".freeze]
s.date = "2018-08-20"
s.email = "[email protected]".freeze
s.homepage = "https://github.com/turbolinks/turbolinks-source-gem".freeze
s.licenses = ["MIT".freeze]
s.rubygems_version = "3.0.3.1".freeze
s.summary = "Turbolinks JavaScript assets".freeze
s.installed_by_version = "3.0.3.1" if s.respond_to? :installed_by_version
end
| 34.65 | 112 | 0.704185 |
bf90d012bf0777e404789b286d83c3390490bd38 | 919 | module ActionView
# = Action View Log Subscriber
#
# Provides functionality so that Rails can output logs from Action View.
class LogSubscriber < ActiveSupport::LogSubscriber
def render_template(event)
message = " Rendered #{from_rails_root(event.payload[:identifier])}"
message << " within #{from_rails_root(event.payload[:layout])}" if event.payload[:layout]
message << (" (%.1fms)" % event.duration)
info(message)
end
alias :render_partial :render_template
alias :render_collection :render_template
# TODO: Ideally, ActionView should have its own logger so it does not depend on AC.logger
def logger
ActionController::Base.logger if defined?(ActionController::Base)
end
protected
def from_rails_root(string)
string.sub("#{Rails.root}/", "").sub(/^app\/views\//, "")
end
end
end
ActionView::LogSubscriber.attach_to :action_view
| 31.689655 | 95 | 0.699674 |
1cbae86d721133ba9f50c7376202cd4d9885fe4b | 4,293 | #
# 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.
#
RSpec.describe Pulsar::Message do
describe "::new" do
it "takes a string" do
m = described_class.new("payload")
expect(m.data).to eq("payload")
end
describe "topic" do
it "is nil when built rather than received" do
m = described_class.new("payload")
expect(m.topic).to be_nil
end
end
describe "properties" do
it "takes properties" do
m = described_class.new("payload", properties: {"a" => "1", "b" => "2"})
expect(m.data).to eq("payload")
expect(m.properties).to eq({"a" => "1", "b" => "2"})
end
it "stringifies non-string properties" do
m = described_class.new("payload", properties: {
"a" => 1,
:b => [2],
})
expect(m.data).to eq("payload")
expect(m.properties).to eq({"a" => "1", "b" => "[2]"})
end
it "takes a lot of properties" do
m = described_class.new("payload", properties: {
"a" => 1,
"b" => [2],
"c" => ("c" * 100000),
"license" => File.read(File.expand_path("../../LICENSE", __dir__)),
})
expect(m.data).to eq("payload")
expect(m.properties["license"]).to match(/Apache License/)
expect(m.properties["license"]).to match(/limitations under the License/)
expect(m.properties["c"]).to match(/^c{100000}$/)
expect(m.properties.values_at("a", "b")).to eq(["1", "[2]"])
end
it "accepts nil properties" do
m = described_class.new("payload", properties: nil)
expect(m.properties).to eq({})
end
end
describe "partition_key" do
it "defaults to blank string" do
m = described_class.new("payload")
expect(m.partition_key).to eq("")
end
it "accepts partition key" do
m = described_class.new("payload", partition_key: "foo")
expect(m.partition_key).to eq("foo")
end
it "accepts nil key" do
m = described_class.new("payload", partition_key: nil)
expect(m.partition_key).to eq("")
end
it "stringifies partition key" do
m = described_class.new("payload", partition_key: :bar)
expect(m.partition_key).to eq("bar")
end
end
describe "ordering_key" do
it "defaults to blank string" do
m = described_class.new("payload")
expect(m.ordering_key).to eq("")
end
it "accepts ordering key" do
m = described_class.new("payload", ordering_key: "foo")
expect(m.ordering_key).to eq("foo")
end
it "accepts nil ordering key" do
m = described_class.new("payload", ordering_key: nil)
expect(m.ordering_key).to eq("")
end
it "stringifies ordering key" do
m = described_class.new("payload", ordering_key: ["o"])
expect(m.ordering_key).to eq(%(["o"]))
end
end
describe "errors" do
it "rejects second arg that is not a hash" do
expect do
described_class.new("payload", [1])
end.to raise_exception(TypeError)
end
it "rejects unknown named arguments" do
expect do
described_class.new("payload", properties: {}, foo: "x")
end.to raise_exception(ArgumentError, /Unknown keyword argument: foo/)
end
it "rejects properties that are not a hash" do
expect do
described_class.new("payload", properties: [])
end.to raise_exception(TypeError)
end
end
end
end
| 31.8 | 81 | 0.607501 |
6a65a6ab33f7f129eb8645db6112d2eea5ef1b8a | 156 | require 'test_helper'
class StaffFileTest < ActiveSupport::TestCase
# Replace this with your real tests.
test "the truth" do
assert true
end
end
| 17.333333 | 45 | 0.737179 |
bfd4814afb3ea32c4df034beaeec31d8f437600f | 61 | class Attachment < ActiveRecord::Base
belongs_to :post
end
| 15.25 | 37 | 0.786885 |
f712eaaf777763a04755edd5b5fbc5e2445fd607 | 2,133 | class HardwareTypesController < ApplicationController
before_action :set_hardware_type, only: [:show, :edit, :update, :destroy]
# GET /hardware_types
# GET /hardware_types.json
def index
@hardware_types = HardwareType.all
end
# GET /hardware_types/1
# GET /hardware_types/1.json
def show
end
# GET /hardware_types/new
def new
@hardware_type = HardwareType.new
end
# GET /hardware_types/1/edit
def edit
end
# POST /hardware_types
# POST /hardware_types.json
def create
@hardware_type = HardwareType.new(hardware_type_params)
respond_to do |format|
if @hardware_type.save
format.html { redirect_to @hardware_type, notice: 'Hardware type was successfully created.' }
format.json { render :show, status: :created, location: @hardware_type }
else
format.html { render :new }
format.json { render json: @hardware_type.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /hardware_types/1
# PATCH/PUT /hardware_types/1.json
def update
respond_to do |format|
if @hardware_type.update(hardware_type_params)
format.html { redirect_to @hardware_type, notice: 'Hardware type was successfully updated.' }
format.json { render :show, status: :ok, location: @hardware_type }
else
format.html { render :edit }
format.json { render json: @hardware_type.errors, status: :unprocessable_entity }
end
end
end
# DELETE /hardware_types/1
# DELETE /hardware_types/1.json
def destroy
@hardware_type.destroy
respond_to do |format|
format.html { redirect_to hardware_types_url, notice: 'Hardware type was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_hardware_type
@hardware_type = HardwareType.find(params[:id])
end
# Only allow a list of trusted parameters through.
def hardware_type_params
params.require(:hardware_type).permit(:code, :name, :description, :category, :order)
end
end
| 28.44 | 105 | 0.694327 |
1cfb99df8a52f007f5b05b0a2cf1c74b3ccf5f44 | 1,262 | class Fwup < Formula
desc "Configurable embedded Linux firmware update creator and runner"
homepage "https://github.com/fhunleth/fwup"
url "https://github.com/fhunleth/fwup/releases/download/v1.2.5/fwup-1.2.5.tar.gz"
sha256 "4b502902fbc653c2e3b74180bbcd27b437677f835a7b3d9bd7bfd3de5f1f294b"
bottle do
cellar :any
sha256 "0291bad0603b96826a9518710b41261b17cd093d0f78bb6a4a80b7113e72465a" => :mojave
sha256 "38de88b1f028e49c4405eb2e9553efb4a18443ec33e67536c820aa0249084c11" => :high_sierra
sha256 "14af77644be3f531267721495c8e26a99ff95fc7474ea316be9138f8e6b5ac8a" => :sierra
sha256 "86fede8a00c63a115abb4845152f7eeb9ebdbfe016eb6551d2d25dfed3a65084" => :el_capitan
sha256 "a1bb7195a25c135c01f9e748f07dd747e801f1dcf86f1bb886d22353fa56cec9" => :x86_64_linux
end
depends_on "pkg-config" => :build
depends_on "confuse"
depends_on "libarchive"
depends_on "libsodium"
def install
system "./configure", "--prefix=#{prefix}", "--disable-dependency-tracking"
system "make", "install"
end
test do
system bin/"fwup", "-g"
assert_predicate testpath/"fwup-key.priv", :exist?, "Failed to create fwup-key.priv!"
assert_predicate testpath/"fwup-key.pub", :exist?, "Failed to create fwup-key.pub!"
end
end
| 39.4375 | 94 | 0.769414 |
bfd40aad16c970316eb8c90492f755aa6245669f | 239 | class CreateConcerts < ActiveRecord::Migration
def change
create_table :concerts do |t|
t.belongs_to :band, index: true
t.belongs_to :venue, index: true
t.datetime :concert_date
t.timestamps
end
end
end
| 21.727273 | 46 | 0.677824 |
ab67cd76ae76565dcc4b2482be5ffd1713ee712c | 642 | # frozen_string_literal: true
require 'rom'
require 'rom-sql'
module SpyAlleyApiMysql
module Relations
class SpyIdentities < ROM::Relation[:sql]
schema(:spy_identities) do
attribute :id, Dry::Types['strict.integer']
attribute :player_id, Dry::Types['strict.integer']
attribute :nationality_id, Dry::Types['strict.integer']
attribute :start_action_id, Dry::Types['strict.integer']
attribute :end_action_id, Dry::Types['strict.integer']
primary_key :id
associations do
belongs_to :player
belongs_to :nationality
end
end
end
end
end
| 24.692308 | 64 | 0.655763 |
e95153c149d36cb9e47fe0cedecb60f21c9c2c65 | 309 | module WorldPayApi
module Api
class CustomerPayment < Base
def create params = {}
@client.post("/Customers/Payments", params).body
end
def update customer_id, params = {}
@client.put("/customers/#{customer_id}/payments", params).body
end
end
end
end
| 22.071429 | 70 | 0.614887 |
bb5b953f51dbcc6d915e489a90806d6a03dbfd61 | 3,066 | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::EachForSimpleLoop, :config do
it 'does not register offense if range startpoint is not constant' do
expect_no_offenses('(a..10).each {}')
end
it 'does not register offense if range endpoint is not constant' do
expect_no_offenses('(0..b).each {}')
end
it 'does not register offense for inline block with parameters' do
expect_no_offenses('(0..10).each { |n| puts n }')
end
it 'does not register offense for multiline block with parameters' do
expect_no_offenses(<<~RUBY)
(0..10).each do |n|
end
RUBY
end
it 'does not register offense for character range' do
expect_no_offenses("('a'..'b').each {}")
end
context 'when using an inclusive end range' do
it 'autocorrects the source with inline block' do
expect_offense(<<~RUBY)
(0..10).each {}
^^^^^^^^^^^^ Use `Integer#times` for a simple loop which iterates a fixed number of times.
RUBY
expect_correction(<<~RUBY)
11.times {}
RUBY
end
it 'autocorrects the source with multiline block' do
expect_offense(<<~RUBY)
(0..10).each do
^^^^^^^^^^^^ Use `Integer#times` for a simple loop which iterates a fixed number of times.
end
RUBY
expect_correction(<<~RUBY)
11.times do
end
RUBY
end
it 'autocorrects the range not starting with zero' do
expect_offense(<<~RUBY)
(3..7).each do
^^^^^^^^^^^ Use `Integer#times` for a simple loop which iterates a fixed number of times.
end
RUBY
expect_correction(<<~RUBY)
5.times do
end
RUBY
end
it 'does not register offense for range not starting with zero and using param' do
expect_no_offenses(<<~RUBY)
(3..7).each do |n|
end
RUBY
end
end
context 'when using an exclusive end range' do
it 'autocorrects the source with inline block' do
expect_offense(<<~RUBY)
(0...10).each {}
^^^^^^^^^^^^^ Use `Integer#times` for a simple loop which iterates a fixed number of times.
RUBY
expect_correction(<<~RUBY)
10.times {}
RUBY
end
it 'autocorrects the source with multiline block' do
expect_offense(<<~RUBY)
(0...10).each do
^^^^^^^^^^^^^ Use `Integer#times` for a simple loop which iterates a fixed number of times.
end
RUBY
expect_correction(<<~RUBY)
10.times do
end
RUBY
end
it 'autocorrects the range not starting with zero' do
expect_offense(<<~RUBY)
(3...7).each do
^^^^^^^^^^^^ Use `Integer#times` for a simple loop which iterates a fixed number of times.
end
RUBY
expect_correction(<<~RUBY)
4.times do
end
RUBY
end
it 'does not register offense for range not starting with zero and using param' do
expect_no_offenses(<<~RUBY)
(3...7).each do |n|
end
RUBY
end
end
end
| 25.764706 | 99 | 0.5985 |
21767cbb46a1f529287453134384cf444db849f7 | 4,100 | require 'rails_helper'
RSpec.describe Bootstrap4RailsComponents::Bootstrap::Components::Card do
let(:card) { described_class.new(options, ActionController::Base.new.view_context) }
let(:options) { {} }
it { expect(described_class).to be < Bootstrap4RailsComponents::Bootstrap::Components::Base }
it_behaves_like 'a component with a consistent initalized construction'
it_behaves_like 'a component that includes the Themeable utility module', component_suite: :bootstrap
describe '#component_family' do
subject { card.component_family }
it { is_expected.to eq :card }
end
describe '#footer' do
subject { card.footer }
context 'when footer is present in options' do
let(:tested_footer) { 'Tested Subtitle' }
let(:options) { { footer: tested_footer } }
it { is_expected.to eq tested_footer }
end
context 'when footer is not present in options' do
let(:options) { {} }
it { is_expected.to eq '' }
end
end
describe '#heading' do
subject { card.heading }
context 'when heading is supplied in :options' do
let(:test_heading) { 'test heading' }
let(:options) { { heading: test_heading } }
it { is_expected.to eq test_heading }
end
context 'when heading is not supplied in options' do
let(:options) { {} }
it { is_expected.to eq '' }
end
end
describe '#subtitle' do
subject { card.subtitle }
context 'when subtitle is present in options' do
let(:tested_subtitle) { 'Tested Subtitle' }
let(:options) { { subtitle: tested_subtitle } }
it { is_expected.to eq tested_subtitle }
end
context 'when subtitle is not present in options' do
let(:options) { {} }
it { is_expected.to eq '' }
end
end
describe '#title' do
subject { card.title }
context 'when title is present in options' do
let(:tested_title) { 'Tested Title' }
let(:options) { { title: tested_title } }
it { is_expected.to eq tested_title }
end
context 'when title is not present in options' do
let(:options) { {} }
it { is_expected.to eq '' }
end
end
describe 'private methods' do
describe '#css_classes' do
subject { card.send(:css_classes) }
let(:options) { { theme: tested_theme, outlined: tested_outline } }
let(:tested_theme) { nil }
let(:tested_outline) { false }
context 'when theme is present' do
context 'when theme is not :light' do
let(:tested_theme) { :secondary }
context 'when outlined is true' do
let(:tested_outline) { true }
it { is_expected.to include "text-#{tested_theme}" }
it { is_expected.not_to include 'text-white' }
end
context 'when outlined is false' do
let(:tested_outline) { false }
it { is_expected.to include 'text-white' }
it { is_expected.not_to include "text-#{tested_theme}" }
end
end
context 'when theme is :light' do
let(:tested_theme) { :light }
it { is_expected.not_to include 'text-white' }
it { is_expected.not_to include "text-#{tested_theme}" }
end
end
end
describe '#default_theme' do
subject { card.send(:default_theme) }
it { is_expected.to be_nil }
end
describe '#non_html_attribute_options' do
subject { card.send(:non_html_attribute_options) }
it { is_expected.to include :footer, :heading, :subtitle, :title }
end
describe '#outlined_css_class_prefix' do
subject { card.send(:outlined_css_class_prefix) }
it { is_expected.to eq 'border-' }
end
describe '#theme_css_class_prefix' do
subject { card.send(:theme_css_class_prefix) }
context 'when card has outlined set to true in options' do
let(:options) { { outlined: true } }
it { is_expected.to eq '' }
end
context 'when card is not outlined' do
let(:options) { { outlined: false } }
it { is_expected.to eq 'bg-' }
end
end
end
end
| 30.827068 | 103 | 0.627561 |
386d07e1c0ead18517611d610ac2314e6cf1c779 | 45,255 | # frozen_string_literal: true
require 'vmpooler/providers/base'
module Vmpooler
class PoolManager
class Provider
class VSphere < Vmpooler::PoolManager::Provider::Base
# The connection_pool method is normally used only for testing
attr_reader :connection_pool
def initialize(config, logger, metrics, redis_connection_pool, name, options)
super(config, logger, metrics, redis_connection_pool, name, options)
task_limit = global_config[:config].nil? || global_config[:config]['task_limit'].nil? ? 10 : global_config[:config]['task_limit'].to_i
# The default connection pool size is:
# Whatever is biggest from:
# - How many pools this provider services
# - Maximum number of cloning tasks allowed
# - Need at least 2 connections so that a pool can have inventory functions performed while cloning etc.
default_connpool_size = [provided_pools.count, task_limit, 2].max
connpool_size = provider_config['connection_pool_size'].nil? ? default_connpool_size : provider_config['connection_pool_size'].to_i
# The default connection pool timeout should be quite large - 60 seconds
connpool_timeout = provider_config['connection_pool_timeout'].nil? ? 60 : provider_config['connection_pool_timeout'].to_i
logger.log('d', "[#{name}] ConnPool - Creating a connection pool of size #{connpool_size} with timeout #{connpool_timeout}")
@connection_pool = Vmpooler::PoolManager::GenericConnectionPool.new(
metrics: metrics,
metric_prefix: "#{name}_provider_connection_pool",
size: connpool_size,
timeout: connpool_timeout
) do
logger.log('d', "[#{name}] Connection Pool - Creating a connection object")
# Need to wrap the vSphere connection object in another object. The generic connection pooler will preserve
# the object reference for the connection, which means it cannot "reconnect" by creating an entirely new connection
# object. Instead by wrapping it in a Hash, the Hash object reference itself never changes but the content of the
# Hash can change, and is preserved across invocations.
new_conn = connect_to_vsphere
{ connection: new_conn }
end
@provider_hosts = {}
@provider_hosts_lock = Mutex.new
@redis = redis_connection_pool
end
# name of the provider class
def name
'vsphere'
end
def folder_configured?(folder_title, base_folder, configured_folders, whitelist)
if whitelist
return true if whitelist.include?(folder_title)
end
return false unless configured_folders.keys.include?(folder_title)
return false unless configured_folders[folder_title] == base_folder
true
end
def destroy_vm_and_log(vm_name, vm_object, pool, data_ttl)
try = 0 if try.nil?
max_tries = 3
@redis.with_metrics do |redis|
redis.multi
redis.srem("vmpooler__completed__#{pool}", vm_name)
redis.hdel("vmpooler__active__#{pool}", vm_name)
redis.hset("vmpooler__vm__#{vm_name}", 'destroy', Time.now)
# Auto-expire metadata key
redis.expire('vmpooler__vm__' + vm_name, (data_ttl * 60 * 60))
redis.exec
end
start = Time.now
if vm_object.is_a? RbVmomi::VIM::Folder
logger.log('s', "[!] [#{pool}] '#{vm_name}' is a folder, bailing on destroying")
raise('Expected VM, but received a folder object')
end
vm_object.PowerOffVM_Task.wait_for_completion if vm_object.runtime&.powerState && vm_object.runtime.powerState == 'poweredOn'
vm_object.Destroy_Task.wait_for_completion
finish = format('%<time>.2f', time: Time.now - start)
logger.log('s', "[-] [#{pool}] '#{vm_name}' destroyed in #{finish} seconds")
metrics.timing("destroy.#{pool}", finish)
rescue RuntimeError
raise
rescue StandardError => e
try += 1
logger.log('s', "[!] [#{pool}] failed to destroy '#{vm_name}' with an error: #{e}")
try >= max_tries ? raise : retry
end
def destroy_folder_and_children(folder_object)
vms = {}
data_ttl = $config[:redis]['data_ttl'].to_i
folder_name = folder_object.name
unless folder_object.childEntity.count == 0
folder_object.childEntity.each do |vm|
vms[vm.name] = vm
end
vms.each do |vm_name, vm_object|
destroy_vm_and_log(vm_name, vm_object, folder_name, data_ttl)
end
end
destroy_folder(folder_object)
end
def destroy_folder(folder_object)
try = 0 if try.nil?
max_tries = 3
logger.log('s', "[-] [#{folder_object.name}] removing unconfigured folder")
folder_object.Destroy_Task.wait_for_completion
rescue StandardError
try += 1
try >= max_tries ? raise : retry
end
def purge_unconfigured_folders(base_folders, configured_folders, whitelist)
@connection_pool.with_metrics do |pool_object|
connection = ensured_vsphere_connection(pool_object)
base_folders.each do |base_folder|
folder_children = get_folder_children(base_folder, connection)
next if folder_children.empty?
folder_children.each do |folder_hash|
folder_hash.each do |folder_title, folder_object|
destroy_folder_and_children(folder_object) unless folder_configured?(folder_title, base_folder, configured_folders, whitelist)
end
end
end
end
end
def get_folder_children(folder_name, connection)
folders = []
propSpecs = { # rubocop:disable Naming/VariableName
entity: self,
inventoryPath: folder_name
}
folder_object = connection.searchIndex.FindByInventoryPath(propSpecs) # rubocop:disable Naming/VariableName
return folders if folder_object.nil?
folder_object.childEntity.each do |folder|
next unless folder.is_a? RbVmomi::VIM::Folder
folders << { folder.name => folder }
end
folders
end
def vms_in_pool(pool_name)
vms = []
@connection_pool.with_metrics do |pool_object|
connection = ensured_vsphere_connection(pool_object)
folder_object = find_vm_folder(pool_name, connection)
return vms if folder_object.nil?
folder_object.childEntity.each do |vm|
vms << { 'name' => vm.name } if vm.is_a? RbVmomi::VIM::VirtualMachine
end
end
vms
end
def select_target_hosts(target, cluster, datacenter)
percentage = 100
dc = "#{datacenter}_#{cluster}"
@provider_hosts_lock.synchronize do
begin
target[dc] = {} unless target.key?(dc)
target[dc]['checking'] = true
hosts_hash = find_least_used_hosts(cluster, datacenter, percentage)
target[dc] = hosts_hash
rescue StandardError
target[dc] = {}
raise
ensure
target[dc]['check_time_finished'] = Time.now
end
end
end
def run_select_hosts(pool_name, target)
now = Time.now
max_age = @config[:config]['host_selection_max_age'] || 60
loop_delay = 5
datacenter = get_target_datacenter_from_config(pool_name)
cluster = get_target_cluster_from_config(pool_name)
raise("cluster for pool #{pool_name} cannot be identified") if cluster.nil?
raise("datacenter for pool #{pool_name} cannot be identified") if datacenter.nil?
dc = "#{datacenter}_#{cluster}"
unless target.key?(dc)
select_target_hosts(target, cluster, datacenter)
return
end
wait_for_host_selection(dc, target, loop_delay, max_age) if target[dc].key?('checking')
if target[dc].key?('check_time_finished')
select_target_hosts(target, cluster, datacenter) if now - target[dc]['check_time_finished'] > max_age
end
end
def wait_for_host_selection(dc, target, maxloop = 0, loop_delay = 1, max_age = 60)
loop_count = 1
until target.key?(dc) && target[dc].key?('check_time_finished')
sleep(loop_delay)
unless maxloop == 0
break if loop_count >= maxloop
loop_count += 1
end
end
return unless target[dc].key?('check_time_finished')
loop_count = 1
while Time.now - target[dc]['check_time_finished'] > max_age
sleep(loop_delay)
unless maxloop == 0
break if loop_count >= maxloop
loop_count += 1
end
end
end
def select_next_host(pool_name, target, architecture = nil)
datacenter = get_target_datacenter_from_config(pool_name)
cluster = get_target_cluster_from_config(pool_name)
raise("cluster for pool #{pool_name} cannot be identified") if cluster.nil?
raise("datacenter for pool #{pool_name} cannot be identified") if datacenter.nil?
dc = "#{datacenter}_#{cluster}"
@provider_hosts_lock.synchronize do
if architecture
raise("there is no candidate in vcenter that meets all the required conditions, that the cluster has available hosts in a 'green' status, not in maintenance mode and not overloaded CPU and memory") unless target[dc].key?('architectures')
host = target[dc]['architectures'][architecture].shift
target[dc]['architectures'][architecture] << host
if target[dc]['hosts'].include?(host)
target[dc]['hosts'].delete(host)
target[dc]['hosts'] << host
end
else
raise("there is no candidate in vcenter that meets all the required conditions, that the cluster has available hosts in a 'green' status, not in maintenance mode and not overloaded CPU and memory") unless target[dc].key?('hosts')
host = target[dc]['hosts'].shift
target[dc]['hosts'] << host
target[dc]['architectures'].each do |arch|
target[dc]['architectures'][arch] = arch.partition { |v| v != host }.flatten if arch.include?(host)
end
end
return host
end
end
def vm_in_target?(pool_name, parent_host, architecture, target)
datacenter = get_target_datacenter_from_config(pool_name)
cluster = get_target_cluster_from_config(pool_name)
raise("cluster for pool #{pool_name} cannot be identified") if cluster.nil?
raise("datacenter for pool #{pool_name} cannot be identified") if datacenter.nil?
dc = "#{datacenter}_#{cluster}"
raise("there is no candidate in vcenter that meets all the required conditions, that the cluster has available hosts in a 'green' status, not in maintenance mode and not overloaded CPU and memory") unless target[dc].key?('hosts')
return true if target[dc]['hosts'].include?(parent_host)
return true if target[dc]['architectures'][architecture].include?(parent_host)
false
end
def get_vm(pool_name, vm_name)
vm_hash = nil
@connection_pool.with_metrics do |pool_object|
connection = ensured_vsphere_connection(pool_object)
vm_object = find_vm(pool_name, vm_name, connection)
return vm_hash if vm_object.nil?
vm_hash = generate_vm_hash(vm_object, pool_name)
end
vm_hash
end
def create_vm(pool_name, new_vmname)
pool = pool_config(pool_name)
raise("Pool #{pool_name} does not exist for the provider #{name}") if pool.nil?
vm_hash = nil
@connection_pool.with_metrics do |pool_object|
connection = ensured_vsphere_connection(pool_object)
# Assume all pool config is valid i.e. not missing
template_path = pool['template']
target_folder_path = pool['folder']
target_datastore = pool['datastore']
target_cluster_name = get_target_cluster_from_config(pool_name)
target_datacenter_name = get_target_datacenter_from_config(pool_name)
# Get the template VM object
raise("Pool #{pool_name} did not specify a full path for the template for the provider #{name}") unless valid_template_path? template_path
template_vm_object = find_template_vm(pool, connection)
# Annotate with creation time, origin template, etc.
# Add extraconfig options that can be queried by vmtools
config_spec = RbVmomi::VIM.VirtualMachineConfigSpec(
annotation: JSON.pretty_generate(
name: new_vmname,
created_by: provider_config['username'],
base_template: template_path,
creation_timestamp: Time.now.utc
),
extraConfig: [
{ key: 'guestinfo.hostname', value: new_vmname }
]
)
# Put the VM in the specified folder and resource pool
relocate_spec = RbVmomi::VIM.VirtualMachineRelocateSpec(
datastore: find_datastore(target_datastore, connection, target_datacenter_name),
diskMoveType: get_disk_backing(pool)
)
manage_host_selection = @config[:config]['manage_host_selection'] if @config[:config].key?('manage_host_selection')
if manage_host_selection
run_select_hosts(pool_name, @provider_hosts)
target_host = select_next_host(pool_name, @provider_hosts)
host_object = find_host_by_dnsname(connection, target_host)
relocate_spec.host = host_object
else
# Choose a cluster/host to place the new VM on
target_cluster_object = find_cluster(target_cluster_name, connection, target_datacenter_name)
relocate_spec.pool = target_cluster_object.resourcePool
end
# Create a clone spec
clone_spec = RbVmomi::VIM.VirtualMachineCloneSpec(
location: relocate_spec,
config: config_spec,
powerOn: true,
template: false
)
begin
vm_target_folder = find_vm_folder(pool_name, connection)
vm_target_folder ||= create_folder(connection, target_folder_path, target_datacenter_name) if @config[:config].key?('create_folders') && (@config[:config]['create_folders'] == true)
rescue StandardError
if @config[:config].key?('create_folders') && (@config[:config]['create_folders'] == true)
vm_target_folder = create_folder(connection, target_folder_path, target_datacenter_name)
else
raise
end
end
raise ArgumentError, "Can not find the configured folder for #{pool_name} #{target_folder_path}" unless vm_target_folder
# Create the new VM
new_vm_object = template_vm_object.CloneVM_Task(
folder: vm_target_folder,
name: new_vmname,
spec: clone_spec
).wait_for_completion
vm_hash = generate_vm_hash(new_vm_object, pool_name)
end
vm_hash
end
def create_disk(pool_name, vm_name, disk_size)
pool = pool_config(pool_name)
raise("Pool #{pool_name} does not exist for the provider #{name}") if pool.nil?
datastore_name = pool['datastore']
raise("Pool #{pool_name} does not have a datastore defined for the provider #{name}") if datastore_name.nil?
@connection_pool.with_metrics do |pool_object|
connection = ensured_vsphere_connection(pool_object)
vm_object = find_vm(pool_name, vm_name, connection)
raise("VM #{vm_name} in pool #{pool_name} does not exist for the provider #{name}") if vm_object.nil?
add_disk(vm_object, disk_size, datastore_name, connection, get_target_datacenter_from_config(pool_name))
end
true
end
def create_snapshot(pool_name, vm_name, new_snapshot_name)
@connection_pool.with_metrics do |pool_object|
connection = ensured_vsphere_connection(pool_object)
vm_object = find_vm(pool_name, vm_name, connection)
raise("VM #{vm_name} in pool #{pool_name} does not exist for the provider #{name}") if vm_object.nil?
old_snap = find_snapshot(vm_object, new_snapshot_name)
raise("Snapshot #{new_snapshot_name} for VM #{vm_name} in pool #{pool_name} already exists for the provider #{name}") unless old_snap.nil?
vm_object.CreateSnapshot_Task(
name: new_snapshot_name,
description: 'vmpooler',
memory: true,
quiesce: true
).wait_for_completion
end
true
end
def revert_snapshot(pool_name, vm_name, snapshot_name)
@connection_pool.with_metrics do |pool_object|
connection = ensured_vsphere_connection(pool_object)
vm_object = find_vm(pool_name, vm_name, connection)
raise("VM #{vm_name} in pool #{pool_name} does not exist for the provider #{name}") if vm_object.nil?
snapshot_object = find_snapshot(vm_object, snapshot_name)
raise("Snapshot #{snapshot_name} for VM #{vm_name} in pool #{pool_name} does not exist for the provider #{name}") if snapshot_object.nil?
snapshot_object.RevertToSnapshot_Task.wait_for_completion
end
true
end
def destroy_vm(pool_name, vm_name)
@connection_pool.with_metrics do |pool_object|
connection = ensured_vsphere_connection(pool_object)
vm_object = find_vm(pool_name, vm_name, connection)
# If a VM doesn't exist then it is effectively deleted
return true if vm_object.nil?
# Poweroff the VM if it's running
vm_object.PowerOffVM_Task.wait_for_completion if vm_object.runtime&.powerState && vm_object.runtime.powerState == 'poweredOn'
# Kill it with fire
vm_object.Destroy_Task.wait_for_completion
end
true
end
def vm_ready?(_pool_name, vm_name)
begin
open_socket(vm_name, global_config[:config]['domain'])
rescue StandardError => _e
return false
end
true
end
# VSphere Helper methods
def get_target_cluster_from_config(pool_name)
pool = pool_config(pool_name)
return nil if pool.nil?
return pool['clone_target'] unless pool['clone_target'].nil?
return global_config[:config]['clone_target'] unless global_config[:config]['clone_target'].nil?
nil
end
def get_target_datacenter_from_config(pool_name)
pool = pool_config(pool_name)
return nil if pool.nil?
return pool['datacenter'] unless pool['datacenter'].nil?
return provider_config['datacenter'] unless provider_config['datacenter'].nil?
nil
end
# Return a hash of VM data
# Provides vmname, hostname, template, poolname, boottime and powerstate information
def generate_vm_hash(vm_object, pool_name)
pool_configuration = pool_config(pool_name)
return nil if pool_configuration.nil?
hostname = vm_object.summary.guest.hostName if vm_object.summary&.guest && vm_object.summary.guest.hostName
boottime = vm_object.runtime.bootTime if vm_object.runtime&.bootTime
powerstate = vm_object.runtime.powerState if vm_object.runtime&.powerState
hash = {
'name' => vm_object.name,
'hostname' => hostname,
'template' => pool_configuration['template'],
'poolname' => pool_name,
'boottime' => boottime,
'powerstate' => powerstate
}
hash
end
# vSphere helper methods
ADAPTER_TYPE = 'lsiLogic'
DISK_TYPE = 'thin'
DISK_MODE = 'persistent'
def ensured_vsphere_connection(connection_pool_object)
connection_pool_object[:connection] = connect_to_vsphere unless vsphere_connection_ok?(connection_pool_object[:connection])
connection_pool_object[:connection]
end
def vsphere_connection_ok?(connection)
_result = connection.serviceInstance.CurrentTime
true
rescue StandardError
false
end
def connect_to_vsphere
max_tries = global_config[:config]['max_tries'] || 3
retry_factor = global_config[:config]['retry_factor'] || 10
try = 1
begin
connection = RbVmomi::VIM.connect host: provider_config['server'],
user: provider_config['username'],
password: provider_config['password'],
insecure: provider_config['insecure'] || false
metrics.increment('connect.open')
connection
rescue StandardError => e
metrics.increment('connect.fail')
raise e if try >= max_tries
sleep(try * retry_factor)
try += 1
retry
end
end
# This should supercede the open_socket method in the Pool Manager
def open_socket(host, domain = nil, timeout = 5, port = 22, &_block)
Timeout.timeout(timeout) do
target_host = host
target_host = "#{host}.#{domain}" if domain
sock = TCPSocket.new target_host, port
begin
yield sock if block_given?
ensure
sock.close
end
end
end
def get_vm_folder_path(vm_object)
# This gives an array starting from the root Datacenters folder all the way to the VM
# [ [Object, String], [Object, String ] ... ]
# It's then reversed so that it now goes from the VM to the Datacenter
full_path = vm_object.path.reverse
# Find the Datacenter object
dc_index = full_path.index { |p| p[0].is_a?(RbVmomi::VIM::Datacenter) }
return nil if dc_index.nil?
# The Datacenter should be at least 2 otherwise there's something
# wrong with the array passed in
# This is the minimum:
# [ VM (0), VM ROOT FOLDER (1), DC (2)]
return nil if dc_index <= 1
# Remove the VM name (Starting position of 1 in the slice)
# Up until the Root VM Folder of DataCenter Node (dc_index - 2)
full_path = full_path.slice(1..dc_index - 2)
# Reverse the array back to normal and
# then convert the array of paths into a '/' seperated string
(full_path.reverse.map { |p| p[1] }).join('/')
end
def add_disk(vm, size, datastore, connection, datacentername)
return false unless size.to_i > 0
vmdk_datastore = find_datastore(datastore, connection, datacentername)
raise("Datastore '#{datastore}' does not exist in datacenter '#{datacentername}'") if vmdk_datastore.nil?
datacenter = connection.serviceInstance.find_datacenter(datacentername)
controller = find_disk_controller(vm)
disk_unit_number = find_disk_unit_number(vm, controller)
disk_count = vm.config.hardware.device.grep(RbVmomi::VIM::VirtualDisk).count
vmdk_file_name = "#{vm['name']}/#{vm['name']}_#{disk_count}.vmdk"
vmdk_spec = RbVmomi::VIM::FileBackedVirtualDiskSpec(
capacityKb: size.to_i * 1024 * 1024,
adapterType: ADAPTER_TYPE,
diskType: DISK_TYPE
)
vmdk_backing = RbVmomi::VIM::VirtualDiskFlatVer2BackingInfo(
datastore: vmdk_datastore,
diskMode: DISK_MODE,
fileName: "[#{datastore}] #{vmdk_file_name}"
)
device = RbVmomi::VIM::VirtualDisk(
backing: vmdk_backing,
capacityInKB: size.to_i * 1024 * 1024,
controllerKey: controller.key,
key: -1,
unitNumber: disk_unit_number
)
device_config_spec = RbVmomi::VIM::VirtualDeviceConfigSpec(
device: device,
operation: RbVmomi::VIM::VirtualDeviceConfigSpecOperation('add')
)
vm_config_spec = RbVmomi::VIM::VirtualMachineConfigSpec(
deviceChange: [device_config_spec]
)
connection.serviceContent.virtualDiskManager.CreateVirtualDisk_Task(
datacenter: datacenter,
name: "[#{datastore}] #{vmdk_file_name}",
spec: vmdk_spec
).wait_for_completion
vm.ReconfigVM_Task(spec: vm_config_spec).wait_for_completion
true
end
def find_datastore(datastorename, connection, datacentername)
datacenter = connection.serviceInstance.find_datacenter(datacentername)
raise("Datacenter #{datacentername} does not exist") if datacenter.nil?
datacenter.find_datastore(datastorename)
end
def find_device(vm, device_name)
vm.config.hardware.device.each do |device|
return device if device.deviceInfo.label == device_name
end
nil
end
def find_disk_controller(vm)
devices = find_disk_devices(vm)
devices.keys.sort.each do |device|
return find_device(vm, devices[device]['device'].deviceInfo.label) if devices[device]['children'].length < 15
end
nil
end
def find_disk_devices(vm)
devices = {}
vm.config.hardware.device.each do |device|
if device.is_a? RbVmomi::VIM::VirtualSCSIController
if devices[device.controllerKey].nil?
devices[device.key] = {}
devices[device.key]['children'] = []
end
devices[device.key]['device'] = device
end
if device.is_a? RbVmomi::VIM::VirtualDisk
if devices[device.controllerKey].nil?
devices[device.controllerKey] = {}
devices[device.controllerKey]['children'] = []
end
devices[device.controllerKey]['children'].push(device)
end
end
devices
end
def find_disk_unit_number(vm, controller)
used_unit_numbers = []
available_unit_numbers = []
devices = find_disk_devices(vm)
devices.keys.sort.each do |c|
next unless controller.key == devices[c]['device'].key
used_unit_numbers.push(devices[c]['device'].scsiCtlrUnitNumber)
devices[c]['children'].each do |disk|
used_unit_numbers.push(disk.unitNumber)
end
end
(0..15).each do |scsi_id|
available_unit_numbers.push(scsi_id) if used_unit_numbers.grep(scsi_id).length <= 0
end
available_unit_numbers.min
end
# Finds a folder object by inventory path
# Params:
# +pool_name+:: the pool to find the folder for
# +connection+:: the vsphere connection object
# returns a ManagedObjectReference for the folder found or nil if not found
def find_vm_folder(pool_name, connection)
# Find a folder by its inventory path and return the object
# Returns nil when the object found is not a folder
pool_configuration = pool_config(pool_name)
return nil if pool_configuration.nil?
folder = pool_configuration['folder']
datacenter = get_target_datacenter_from_config(pool_name)
return nil if datacenter.nil?
propSpecs = { # rubocop:disable Naming/VariableName
entity: self,
inventoryPath: "#{datacenter}/vm/#{folder}"
}
folder_object = connection.searchIndex.FindByInventoryPath(propSpecs) # rubocop:disable Naming/VariableName
return nil unless folder_object.class == RbVmomi::VIM::Folder
folder_object
end
# Returns an array containing cumulative CPU and memory utilization of a host, and its object reference
# Params:
# +model+:: CPU arch version to match on
# +limit+:: Hard limit for CPU or memory utilization beyond which a host is excluded for deployments
# returns nil if one on these conditions is true:
# the model param is defined and cannot be found
# the host is in maintenance mode
# the host status is not 'green'
# the cpu or memory utilization is bigger than the limit param
def get_host_utilization(host, model = nil, limit = 90)
limit = @config[:config]['utilization_limit'] if @config[:config].key?('utilization_limit')
if model
return nil unless host_has_cpu_model?(host, model)
end
return nil if host.runtime.inMaintenanceMode
return nil unless host.overallStatus == 'green'
return nil unless host.configIssue.empty?
cpu_utilization = cpu_utilization_for host
memory_utilization = memory_utilization_for host
return nil if cpu_utilization.nil?
return nil if cpu_utilization == 0.0
return nil if memory_utilization.nil?
return nil if memory_utilization == 0.0
return nil if cpu_utilization > limit
return nil if memory_utilization > limit
[cpu_utilization, host]
end
def host_has_cpu_model?(host, model)
get_host_cpu_arch_version(host) == model
end
def get_host_cpu_arch_version(host)
cpu_model = host.hardware.cpuPkg[0].description
cpu_model_parts = cpu_model.split
arch_version = cpu_model_parts[4]
arch_version
end
def cpu_utilization_for(host)
cpu_usage = host.summary.quickStats.overallCpuUsage
return nil if cpu_usage.nil?
cpu_size = host.summary.hardware.cpuMhz * host.summary.hardware.numCpuCores
cpu_usage.fdiv(cpu_size) * 100
end
def memory_utilization_for(host)
memory_usage = host.summary.quickStats.overallMemoryUsage
return nil if memory_usage.nil?
memory_size = host.summary.hardware.memorySize / 1024 / 1024
memory_usage.fdiv(memory_size) * 100
end
def get_average_cluster_utilization(hosts)
utilization_counts = hosts.map { |host| host[0] }
utilization_counts.inject(:+) / hosts.count
end
def build_compatible_hosts_lists(hosts, percentage)
hosts_with_arch_versions = hosts.map do |h|
{
'utilization' => h[0],
'host_object' => h[1],
'architecture' => get_host_cpu_arch_version(h[1])
}
end
versions = hosts_with_arch_versions.map { |host| host['architecture'] }.uniq
architectures = {}
versions.each do |version|
architectures[version] = []
end
hosts_with_arch_versions.each do |h|
architectures[h['architecture']] << [h['utilization'], h['host_object'], h['architecture']]
end
versions.each do |version|
targets = select_least_used_hosts(architectures[version], percentage)
architectures[version] = targets
end
architectures
end
def select_least_used_hosts(hosts, percentage)
raise('Provided hosts list to select_least_used_hosts is empty') if hosts.empty?
average_utilization = get_average_cluster_utilization(hosts)
least_used_hosts = []
hosts.each do |host|
least_used_hosts << host if host[0] <= average_utilization
end
hosts_to_select = (hosts.count * (percentage / 100.0)).to_int
hosts_to_select = hosts.count - 1 if percentage == 100
least_used_hosts.sort[0..hosts_to_select].map { |host| host[1].name }
end
def find_least_used_hosts(cluster, datacentername, percentage)
@connection_pool.with_metrics do |pool_object|
connection = ensured_vsphere_connection(pool_object)
cluster_object = find_cluster(cluster, connection, datacentername)
raise("Cluster #{cluster} cannot be found") if cluster_object.nil?
target_hosts = get_cluster_host_utilization(cluster_object)
raise("there is no candidate in vcenter that meets all the required conditions, that the cluster has available hosts in a 'green' status, not in maintenance mode and not overloaded CPU and memory'") if target_hosts.empty?
architectures = build_compatible_hosts_lists(target_hosts, percentage)
least_used_hosts = select_least_used_hosts(target_hosts, percentage)
{
'hosts' => least_used_hosts,
'architectures' => architectures
}
end
end
def find_host_by_dnsname(connection, dnsname)
host_object = connection.searchIndex.FindByDnsName(dnsName: dnsname, vmSearch: false)
return nil if host_object.nil?
host_object
end
def find_least_used_host(cluster, connection, datacentername)
cluster_object = find_cluster(cluster, connection, datacentername)
target_hosts = get_cluster_host_utilization(cluster_object)
raise("There is no host candidate in vcenter that meets all the required conditions, check that the cluster has available hosts in a 'green' status, not in maintenance mode and not overloaded CPU and memory'") if target_hosts.empty?
least_used_host = target_hosts.min[1]
least_used_host
end
def find_cluster(cluster, connection, datacentername)
datacenter = connection.serviceInstance.find_datacenter(datacentername)
raise("Datacenter #{datacentername} does not exist") if datacenter.nil?
# In the event the cluster is not a direct descendent of the
# datacenter, we use a ContainerView to leverage its recursive
# search. This will find clusters which are, for example, in
# folders under the datacenter. This will also find standalone
# hosts which are not part of a cluster.
cv = connection.serviceContent.viewManager.CreateContainerView(
container: datacenter.hostFolder,
type: ['ComputeResource', 'ClusterComputeResource'],
recursive: true
)
cluster = cv.view.find { |cluster_object| cluster_object.name == cluster }
cv.DestroyView
cluster
end
def get_cluster_host_utilization(cluster, model = nil)
cluster_hosts = []
cluster.host.each do |host|
host_usage = get_host_utilization(host, model)
cluster_hosts << host_usage if host_usage
end
cluster_hosts
end
def find_least_used_vpshere_compatible_host(vm)
source_host = vm.summary.runtime.host
model = get_host_cpu_arch_version(source_host)
cluster = source_host.parent
target_hosts = get_cluster_host_utilization(cluster, model)
raise("There is no host candidate in vcenter that meets all the required conditions, check that the cluster has available hosts in a 'green' status, not in maintenance mode and not overloaded CPU and memory'") if target_hosts.empty?
target_host = target_hosts.min[1]
[target_host, target_host.name]
end
def find_snapshot(vm, snapshotname)
get_snapshot_list(vm.snapshot.rootSnapshotList, snapshotname) if vm.snapshot
end
def build_propSpecs(datacenter, folder, vmname) # rubocop:disable Naming/MethodName
propSpecs = { # rubocop:disable Naming/VariableName
entity => self,
:inventoryPath => "#{datacenter}/vm/#{folder}/#{vmname}"
}
propSpecs # rubocop:disable Naming/VariableName
end
def find_vm(pool_name, vmname, connection)
# Find a VM by its inventory path and return the VM object
# Returns nil when a VM, or pool configuration, cannot be found
pool_configuration = pool_config(pool_name)
return nil if pool_configuration.nil?
folder = pool_configuration['folder']
datacenter = get_target_datacenter_from_config(pool_name)
return nil if datacenter.nil?
propSpecs = { # rubocop:disable Naming/VariableName
entity: self,
inventoryPath: "#{datacenter}/vm/#{folder}/#{vmname}"
}
connection.searchIndex.FindByInventoryPath(propSpecs) # rubocop:disable Naming/VariableName
end
def get_base_vm_container_from(connection)
view_manager = connection.serviceContent.viewManager
view_manager.CreateContainerView(
container: connection.serviceContent.rootFolder,
recursive: true,
type: ['VirtualMachine']
)
end
def get_snapshot_list(tree, snapshotname)
snapshot = nil
tree.each do |child|
if child.name == snapshotname
snapshot ||= child.snapshot
else
snapshot ||= get_snapshot_list(child.childSnapshotList, snapshotname)
end
end
snapshot
end
def get_vm_details(pool_name, vm_name, connection)
vm_object = find_vm(pool_name, vm_name, connection)
return nil if vm_object.nil?
parent_host_object = vm_object.summary.runtime.host if vm_object.summary&.runtime && vm_object.summary.runtime.host
raise('Unable to determine which host the VM is running on') if parent_host_object.nil?
parent_host = parent_host_object.name
architecture = get_host_cpu_arch_version(parent_host_object)
{
'host_name' => parent_host,
'object' => vm_object,
'architecture' => architecture
}
end
def migration_enabled?(config)
migration_limit = config[:config]['migration_limit']
return false unless migration_limit.is_a? Integer
return true if migration_limit > 0
false
end
def migrate_vm(pool_name, vm_name)
@connection_pool.with_metrics do |pool_object|
begin
connection = ensured_vsphere_connection(pool_object)
vm_hash = get_vm_details(pool_name, vm_name, connection)
@redis.with_metrics do |redis|
redis.hset("vmpooler__vm__#{vm_name}", 'host', vm_hash['host_name'])
migration_count = redis.scard('vmpooler__migration')
migration_limit = @config[:config]['migration_limit'] if @config[:config].key?('migration_limit')
if migration_enabled? @config
if migration_count >= migration_limit
logger.log('s', "[ ] [#{pool_name}] '#{vm_name}' is running on #{vm_hash['host_name']}. No migration will be evaluated since the migration_limit has been reached")
break
end
run_select_hosts(pool_name, @provider_hosts)
if vm_in_target?(pool_name, vm_hash['host_name'], vm_hash['architecture'], @provider_hosts)
logger.log('s', "[ ] [#{pool_name}] No migration required for '#{vm_name}' running on #{vm_hash['host_name']}")
else
migrate_vm_to_new_host(pool_name, vm_name, vm_hash, connection)
end
else
logger.log('s', "[ ] [#{pool_name}] '#{vm_name}' is running on #{vm_hash['host_name']}")
end
end
rescue StandardError
logger.log('s', "[!] [#{pool_name}] '#{vm_name}' is running on #{vm_hash['host_name']}")
raise
end
end
end
def migrate_vm_to_new_host(pool_name, vm_name, vm_hash, connection)
@redis.with_metrics do |redis|
redis.sadd('vmpooler__migration', vm_name)
end
target_host_name = select_next_host(pool_name, @provider_hosts, vm_hash['architecture'])
target_host_object = find_host_by_dnsname(connection, target_host_name)
finish = migrate_vm_and_record_timing(pool_name, vm_name, vm_hash, target_host_object, target_host_name)
@redis.with_metrics do |redis|
redis.multi
redis.hset("vmpooler__vm__#{vm_name}", 'host', target_host_name)
redis.hset("vmpooler__vm__#{vm_name}", 'migrated', true)
redis.exec
end
logger.log('s', "[>] [#{pool_name}] '#{vm_name}' migrated from #{vm_hash['host_name']} to #{target_host_name} in #{finish} seconds")
ensure
@redis.with_metrics do |redis|
redis.srem('vmpooler__migration', vm_name)
end
end
def migrate_vm_and_record_timing(pool_name, vm_name, vm_hash, target_host_object, dest_host_name)
start = Time.now
migrate_vm_host(vm_hash['object'], target_host_object)
finish = format('%<time>.2f', time: Time.now - start)
metrics.timing("migrate.#{pool_name}", finish)
metrics.increment("migrate_from.#{vm_hash['host_name']}")
metrics.increment("migrate_to.#{dest_host_name}")
@redis.with_metrics do |redis|
checkout_to_migration = format('%<time>.2f', time: Time.now - Time.parse(redis.hget("vmpooler__vm__#{vm_name}", 'checkout')))
redis.multi
redis.hset("vmpooler__vm__#{vm_name}", 'migration_time', finish)
redis.hset("vmpooler__vm__#{vm_name}", 'checkout_to_migration', checkout_to_migration)
redis.exec
end
finish
end
def migrate_vm_host(vm_object, host)
relospec = RbVmomi::VIM.VirtualMachineRelocateSpec(host: host)
vm_object.RelocateVM_Task(spec: relospec).wait_for_completion
end
def create_folder(connection, new_folder, datacenter)
dc = connection.serviceInstance.find_datacenter(datacenter)
folder_object = dc.vmFolder.traverse(new_folder, RbVmomi::VIM::Folder, true)
raise("Cannot create folder #{new_folder}") if folder_object.nil?
folder_object
end
def find_template_vm(pool, connection)
datacenter = get_target_datacenter_from_config(pool['name'])
raise('cannot find datacenter') if datacenter.nil?
propSpecs = { # rubocop:disable Naming/VariableName
entity: self,
inventoryPath: "#{datacenter}/vm/#{pool['template']}"
}
template_vm_object = connection.searchIndex.FindByInventoryPath(propSpecs) # rubocop:disable Naming/VariableName
raise("Pool #{pool['name']} specifies a template VM of #{pool['template']} which does not exist for the provider #{name}") if template_vm_object.nil?
template_vm_object
end
def create_template_delta_disks(pool)
@connection_pool.with_metrics do |pool_object|
connection = ensured_vsphere_connection(pool_object)
template_vm_object = find_template_vm(pool, connection)
template_vm_object.add_delta_disk_layer_on_all_disks
end
end
def valid_template_path?(template)
return false unless template.include?('/')
return false if template[0] == '/'
return false if template[-1] == '/'
true
end
def get_disk_backing(pool)
return :moveChildMostDiskBacking if linked_clone?(pool)
:moveAllDiskBackingsAndConsolidate
end
def linked_clone?(pool)
return if pool['create_linked_clone'] == false
return true if pool['create_linked_clone']
return true if @config[:config]['create_linked_clones']
end
end
end
end
end
| 41.140909 | 251 | 0.619534 |
6ad1655d156982e01d7cf00f8fda1d71b4e293c8 | 26,186 | RSpec.describe HrrRbRelaxedXML::Document do
describe "when instantiated with no args" do
let(:xml_doc){ described_class.new }
it "returns HrrRbRelaxedXML::Document instance" do
expect( xml_doc ).to be_instance_of described_class
end
it "returns REXML::Document kind instance" do
expect( xml_doc ).to be_kind_of REXML::Document
end
it "raises ArgumentError when #add_element with no args" do
expect { xml_doc.add_element }.to raise_error ArgumentError
end
it "raises RuntimeError when #add_element with nil arg" do
expect { xml_doc.add_element nil }.to raise_error RuntimeError
end
it "can add element with name argument and store it as element" do
xml_doc.add_element 'root1'
expect( xml_doc.elements.size ).to eq 1
expect( xml_doc.elements[1].name ).to eq 'root1'
expect( xml_doc.elements[1].attributes.size ).to eq 0
end
it "can add element with name argument with attribute and store it as element" do
xml_doc.add_element 'root1', {'attr1' => 'val1'}
expect( xml_doc.elements.size ).to eq 1
expect( xml_doc.elements[1].name ).to eq 'root1'
expect( xml_doc.elements[1].attributes.size ).to eq 1
expect( xml_doc.elements[1].attributes['attr1'] ).to eq 'val1'
end
it "can add element with name argument multiple times and store them as elements" do
xml_doc.add_element 'root1', {'attr1' => 'val1'}
xml_doc.add_element 'root2'
xml_doc.add_element 'root3', {'attr3' => 'val3'}
xml_doc.add_element 'root4'
xml_doc.add_element 'root5', {'attr5' => 'val5'}
expect( xml_doc.elements.size ).to eq 5
expect( xml_doc.elements[1].name ).to eq 'root1'
expect( xml_doc.elements[2].name ).to eq 'root2'
expect( xml_doc.elements[3].name ).to eq 'root3'
expect( xml_doc.elements[4].name ).to eq 'root4'
expect( xml_doc.elements[5].name ).to eq 'root5'
expect( xml_doc.elements[1].attributes.size ).to eq 1
expect( xml_doc.elements[2].attributes.size ).to eq 0
expect( xml_doc.elements[3].attributes.size ).to eq 1
expect( xml_doc.elements[4].attributes.size ).to eq 0
expect( xml_doc.elements[5].attributes.size ).to eq 1
expect( xml_doc.elements[1].attributes['attr1'] ).to eq 'val1'
expect( xml_doc.elements[2].attributes['attr2'] ).to be nil
expect( xml_doc.elements[3].attributes['attr3'] ).to eq 'val3'
expect( xml_doc.elements[4].attributes['attr4'] ).to be nil
expect( xml_doc.elements[5].attributes['attr5'] ).to eq 'val5'
end
end
describe "when instantiated with XML string" do
let(:xml_doc){ described_class.new xml_str }
describe "with one root element with no attributes" do
describe "with no XML declaration" do
let(:xml_str){
<<-EOB
<root1>
<dummy1 />
</root1>
EOB
}
it "returns HrrRbRelaxedXML::Document instance" do
expect( xml_doc ).to be_instance_of described_class
end
it "returns REXML::Document kind instance" do
expect( xml_doc ).to be_kind_of REXML::Document
end
it "has default XML declaration not to be written" do
expect( xml_doc.xml_decl.version ).to eq "1.0"
expect( xml_doc.xml_decl.encoding ).to eq "UTF-8"
expect( xml_doc.xml_decl.standalone ).to be nil
expect( xml_doc.xml_decl.writethis ).to be false
end
it "has one root element" do
expect( xml_doc.elements.size ).to eq 1
expect( xml_doc.elements[1].name ).to eq 'root1'
expect( xml_doc.elements[1].attributes.size ).to eq 0
expect( xml_doc.elements[1].attributes['attr1'] ).to be nil
end
it "can add element with name argument multiple times and store them as elements" do
xml_doc.add_element 'root2'
xml_doc.add_element 'root3', {'attr3' => 'val3'}
xml_doc.add_element 'root4'
xml_doc.add_element 'root5', {'attr5' => 'val5'}
expect( xml_doc.elements.size ).to eq 5
expect( xml_doc.elements[1].name ).to eq 'root1'
expect( xml_doc.elements[2].name ).to eq 'root2'
expect( xml_doc.elements[3].name ).to eq 'root3'
expect( xml_doc.elements[4].name ).to eq 'root4'
expect( xml_doc.elements[5].name ).to eq 'root5'
expect( xml_doc.elements[1].attributes.size ).to eq 0
expect( xml_doc.elements[2].attributes.size ).to eq 0
expect( xml_doc.elements[3].attributes.size ).to eq 1
expect( xml_doc.elements[4].attributes.size ).to eq 0
expect( xml_doc.elements[5].attributes.size ).to eq 1
expect( xml_doc.elements[1].attributes['attr1'] ).to be nil
expect( xml_doc.elements[2].attributes['attr2'] ).to be nil
expect( xml_doc.elements[3].attributes['attr3'] ).to eq 'val3'
expect( xml_doc.elements[4].attributes['attr4'] ).to be nil
expect( xml_doc.elements[5].attributes['attr5'] ).to eq 'val5'
end
end
describe "with XML declaration" do
let(:xml_str){
<<-EOB
<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>
<root1>
<dummy />
</root1>
EOB
}
it "returns HrrRbRelaxedXML::Document instance" do
expect( xml_doc ).to be_instance_of described_class
end
it "returns REXML::Document kind instance" do
expect( xml_doc ).to be_kind_of REXML::Document
end
it "has XML declaration to be written" do
expect( xml_doc.xml_decl.version ).to eq "1.0"
expect( xml_doc.xml_decl.encoding ).to eq "UTF-8"
expect( xml_doc.xml_decl.standalone ).to eq "yes"
expect( xml_doc.xml_decl.writethis ).to be true
end
it "has one root element" do
expect( xml_doc.elements.size ).to eq 1
expect( xml_doc.elements[1].name ).to eq 'root1'
expect( xml_doc.elements[1].attributes.size ).to eq 0
expect( xml_doc.elements[1].attributes['attr1'] ).to be nil
end
it "can add element with name argument multiple times and store them as elements" do
xml_doc.add_element 'root2'
xml_doc.add_element 'root3', {'attr3' => 'val3'}
xml_doc.add_element 'root4'
xml_doc.add_element 'root5', {'attr5' => 'val5'}
expect( xml_doc.elements.size ).to eq 5
expect( xml_doc.elements[1].name ).to eq 'root1'
expect( xml_doc.elements[2].name ).to eq 'root2'
expect( xml_doc.elements[3].name ).to eq 'root3'
expect( xml_doc.elements[4].name ).to eq 'root4'
expect( xml_doc.elements[5].name ).to eq 'root5'
expect( xml_doc.elements[1].attributes.size ).to eq 0
expect( xml_doc.elements[2].attributes.size ).to eq 0
expect( xml_doc.elements[3].attributes.size ).to eq 1
expect( xml_doc.elements[4].attributes.size ).to eq 0
expect( xml_doc.elements[5].attributes.size ).to eq 1
expect( xml_doc.elements[1].attributes['attr1'] ).to be nil
expect( xml_doc.elements[2].attributes['attr2'] ).to be nil
expect( xml_doc.elements[3].attributes['attr3'] ).to eq 'val3'
expect( xml_doc.elements[4].attributes['attr4'] ).to be nil
expect( xml_doc.elements[5].attributes['attr5'] ).to eq 'val5'
end
end
end
describe "with one root element with attributes" do
describe "with no XML declaration" do
let(:xml_str){
<<-EOB
<root1 attr1="val1">
<dummy1 />
</root1>
EOB
}
it "returns HrrRbRelaxedXML::Document instance" do
expect( xml_doc ).to be_instance_of described_class
end
it "returns REXML::Document kind instance" do
expect( xml_doc ).to be_kind_of REXML::Document
end
it "has default XML declaration not to be written" do
expect( xml_doc.xml_decl.version ).to eq "1.0"
expect( xml_doc.xml_decl.encoding ).to eq "UTF-8"
expect( xml_doc.xml_decl.standalone ).to be nil
expect( xml_doc.xml_decl.writethis ).to be false
end
it "has one root element" do
expect( xml_doc.elements.size ).to eq 1
expect( xml_doc.elements[1].name ).to eq 'root1'
expect( xml_doc.elements[1].attributes.size ).to eq 1
expect( xml_doc.elements[1].attributes['attr1'] ).to eq "val1"
end
it "can add element with name argument multiple times and store them as elements" do
xml_doc.add_element 'root2'
xml_doc.add_element 'root3', {'attr3' => 'val3'}
xml_doc.add_element 'root4'
xml_doc.add_element 'root5', {'attr5' => 'val5'}
expect( xml_doc.elements.size ).to eq 5
expect( xml_doc.elements[1].name ).to eq 'root1'
expect( xml_doc.elements[2].name ).to eq 'root2'
expect( xml_doc.elements[3].name ).to eq 'root3'
expect( xml_doc.elements[4].name ).to eq 'root4'
expect( xml_doc.elements[5].name ).to eq 'root5'
expect( xml_doc.elements[1].attributes.size ).to eq 1
expect( xml_doc.elements[2].attributes.size ).to eq 0
expect( xml_doc.elements[3].attributes.size ).to eq 1
expect( xml_doc.elements[4].attributes.size ).to eq 0
expect( xml_doc.elements[5].attributes.size ).to eq 1
expect( xml_doc.elements[1].attributes['attr1'] ).to eq "val1"
expect( xml_doc.elements[2].attributes['attr2'] ).to be nil
expect( xml_doc.elements[3].attributes['attr3'] ).to eq 'val3'
expect( xml_doc.elements[4].attributes['attr4'] ).to be nil
expect( xml_doc.elements[5].attributes['attr5'] ).to eq 'val5'
end
end
describe "with XML declaration" do
let(:xml_str){
<<-EOB
<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>
<root1 attr1="val1">
<dummy />
</root1>
EOB
}
it "returns HrrRbRelaxedXML::Document instance" do
expect( xml_doc ).to be_instance_of described_class
end
it "returns REXML::Document kind instance" do
expect( xml_doc ).to be_kind_of REXML::Document
end
it "has XML declaration to be written" do
expect( xml_doc.xml_decl.version ).to eq "1.0"
expect( xml_doc.xml_decl.encoding ).to eq "UTF-8"
expect( xml_doc.xml_decl.standalone ).to eq "yes"
expect( xml_doc.xml_decl.writethis ).to be true
end
it "has one root element" do
expect( xml_doc.elements.size ).to eq 1
expect( xml_doc.elements[1].name ).to eq 'root1'
expect( xml_doc.elements[1].attributes.size ).to eq 1
expect( xml_doc.elements[1].attributes['attr1'] ).to eq "val1"
end
it "can add element with name argument multiple times and store them as elements" do
xml_doc.add_element 'root2'
xml_doc.add_element 'root3', {'attr3' => 'val3'}
xml_doc.add_element 'root4'
xml_doc.add_element 'root5', {'attr5' => 'val5'}
expect( xml_doc.elements.size ).to eq 5
expect( xml_doc.elements[1].name ).to eq 'root1'
expect( xml_doc.elements[2].name ).to eq 'root2'
expect( xml_doc.elements[3].name ).to eq 'root3'
expect( xml_doc.elements[4].name ).to eq 'root4'
expect( xml_doc.elements[5].name ).to eq 'root5'
expect( xml_doc.elements[1].attributes.size ).to eq 1
expect( xml_doc.elements[2].attributes.size ).to eq 0
expect( xml_doc.elements[3].attributes.size ).to eq 1
expect( xml_doc.elements[4].attributes.size ).to eq 0
expect( xml_doc.elements[5].attributes.size ).to eq 1
expect( xml_doc.elements[1].attributes['attr1'] ).to eq "val1"
expect( xml_doc.elements[2].attributes['attr2'] ).to be nil
expect( xml_doc.elements[3].attributes['attr3'] ).to eq 'val3'
expect( xml_doc.elements[4].attributes['attr4'] ).to be nil
expect( xml_doc.elements[5].attributes['attr5'] ).to eq 'val5'
end
end
end
describe "with multiple root elements with attributes" do
describe "with no XML declaration" do
let(:xml_str){
<<-EOB
<root1 attr1="val1">
<dummy1 />
</root1>
<root2>
<dummy2 />
</root2>
<root3 attr3="val3">
<dummy3 />
</root3>
EOB
}
it "returns HrrRbRelaxedXML::Document instance" do
expect( xml_doc ).to be_instance_of described_class
end
it "returns REXML::Document kind instance" do
expect( xml_doc ).to be_kind_of REXML::Document
end
it "has default XML declaration not to be written" do
expect( xml_doc.xml_decl.version ).to eq "1.0"
expect( xml_doc.xml_decl.encoding ).to eq "UTF-8"
expect( xml_doc.xml_decl.standalone ).to be nil
expect( xml_doc.xml_decl.writethis ).to be false
end
it "has multiple root elements" do
expect( xml_doc.elements.size ).to eq 3
expect( xml_doc.elements[1].name ).to eq 'root1'
expect( xml_doc.elements[2].name ).to eq 'root2'
expect( xml_doc.elements[3].name ).to eq 'root3'
expect( xml_doc.elements[1].attributes.size ).to eq 1
expect( xml_doc.elements[2].attributes.size ).to eq 0
expect( xml_doc.elements[3].attributes.size ).to eq 1
expect( xml_doc.elements[1].attributes['attr1'] ).to eq 'val1'
expect( xml_doc.elements[2].attributes['attr2'] ).to be nil
expect( xml_doc.elements[3].attributes['attr3'] ).to eq 'val3'
end
it "can add element with name argument multiple times and store them as elements" do
xml_doc.add_element 'root4'
xml_doc.add_element 'root5', {'attr5' => 'val5'}
expect( xml_doc.elements.size ).to eq 5
expect( xml_doc.elements[1].name ).to eq 'root1'
expect( xml_doc.elements[2].name ).to eq 'root2'
expect( xml_doc.elements[3].name ).to eq 'root3'
expect( xml_doc.elements[4].name ).to eq 'root4'
expect( xml_doc.elements[5].name ).to eq 'root5'
expect( xml_doc.elements[1].attributes.size ).to eq 1
expect( xml_doc.elements[2].attributes.size ).to eq 0
expect( xml_doc.elements[3].attributes.size ).to eq 1
expect( xml_doc.elements[4].attributes.size ).to eq 0
expect( xml_doc.elements[5].attributes.size ).to eq 1
expect( xml_doc.elements[1].attributes['attr1'] ).to eq 'val1'
expect( xml_doc.elements[2].attributes['attr2'] ).to be nil
expect( xml_doc.elements[3].attributes['attr3'] ).to eq 'val3'
expect( xml_doc.elements[4].attributes['attr4'] ).to be nil
expect( xml_doc.elements[5].attributes['attr5'] ).to eq 'val5'
end
end
describe "with XML declaration" do
let(:xml_str){
<<-EOB
<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>
<root1 attr1="val1">
<dummy />
</root1>
<root2>
<dummy2 />
</root2>
<root3 attr3="val3">
<dummy3 />
</root3>
EOB
}
it "returns HrrRbRelaxedXML::Document instance" do
expect( xml_doc ).to be_instance_of described_class
end
it "returns REXML::Document kind instance" do
expect( xml_doc ).to be_kind_of REXML::Document
end
it "has XML declaration to be written" do
expect( xml_doc.xml_decl.version ).to eq "1.0"
expect( xml_doc.xml_decl.encoding ).to eq "UTF-8"
expect( xml_doc.xml_decl.standalone ).to eq "yes"
expect( xml_doc.xml_decl.writethis ).to be true
end
it "has multiple root elements" do
expect( xml_doc.elements.size ).to eq 3
expect( xml_doc.elements[1].name ).to eq 'root1'
expect( xml_doc.elements[2].name ).to eq 'root2'
expect( xml_doc.elements[3].name ).to eq 'root3'
expect( xml_doc.elements[1].attributes.size ).to eq 1
expect( xml_doc.elements[2].attributes.size ).to eq 0
expect( xml_doc.elements[3].attributes.size ).to eq 1
expect( xml_doc.elements[1].attributes['attr1'] ).to eq 'val1'
expect( xml_doc.elements[2].attributes['attr2'] ).to be nil
expect( xml_doc.elements[3].attributes['attr3'] ).to eq 'val3'
end
it "can add element with name argument multiple times and store them as elements" do
xml_doc.add_element 'root4'
xml_doc.add_element 'root5', {'attr5' => 'val5'}
expect( xml_doc.elements.size ).to eq 5
expect( xml_doc.elements[1].name ).to eq 'root1'
expect( xml_doc.elements[2].name ).to eq 'root2'
expect( xml_doc.elements[3].name ).to eq 'root3'
expect( xml_doc.elements[4].name ).to eq 'root4'
expect( xml_doc.elements[5].name ).to eq 'root5'
expect( xml_doc.elements[1].attributes.size ).to eq 1
expect( xml_doc.elements[2].attributes.size ).to eq 0
expect( xml_doc.elements[3].attributes.size ).to eq 1
expect( xml_doc.elements[4].attributes.size ).to eq 0
expect( xml_doc.elements[5].attributes.size ).to eq 1
expect( xml_doc.elements[1].attributes['attr1'] ).to eq 'val1'
expect( xml_doc.elements[2].attributes['attr2'] ).to be nil
expect( xml_doc.elements[3].attributes['attr3'] ).to eq 'val3'
expect( xml_doc.elements[4].attributes['attr4'] ).to be nil
expect( xml_doc.elements[5].attributes['attr5'] ).to eq 'val5'
end
end
end
describe "with multiple root elements with the same name" do
let(:xml_str){
<<-EOB
<root attr1="val1">
<dummy1 />
</root>
<root>
<dummy2 />
</root>
<root attr3="val3">
<dummy3 />
</root>
EOB
}
it "returns HrrRbRelaxedXML::Document instance" do
expect( xml_doc ).to be_instance_of described_class
end
it "returns REXML::Document kind instance" do
expect( xml_doc ).to be_kind_of REXML::Document
end
it "has multiple root elements" do
expect( xml_doc.elements.size ).to eq 3
expect( xml_doc.elements[1].name ).to eq 'root'
expect( xml_doc.elements[2].name ).to eq 'root'
expect( xml_doc.elements[3].name ).to eq 'root'
expect( xml_doc.elements[1].attributes.size ).to eq 1
expect( xml_doc.elements[2].attributes.size ).to eq 0
expect( xml_doc.elements[3].attributes.size ).to eq 1
expect( xml_doc.elements[1].attributes['attr1'] ).to eq 'val1'
expect( xml_doc.elements[2].attributes['attr2'] ).to be nil
expect( xml_doc.elements[3].attributes['attr3'] ).to eq 'val3'
end
it "can add element with name argument multiple times and store them as elements" do
xml_doc.add_element 'root'
xml_doc.add_element 'root', {'attr5' => 'val5'}
expect( xml_doc.elements.size ).to eq 5
expect( xml_doc.elements[1].name ).to eq 'root'
expect( xml_doc.elements[2].name ).to eq 'root'
expect( xml_doc.elements[3].name ).to eq 'root'
expect( xml_doc.elements[4].name ).to eq 'root'
expect( xml_doc.elements[5].name ).to eq 'root'
expect( xml_doc.elements[1].attributes.size ).to eq 1
expect( xml_doc.elements[2].attributes.size ).to eq 0
expect( xml_doc.elements[3].attributes.size ).to eq 1
expect( xml_doc.elements[4].attributes.size ).to eq 0
expect( xml_doc.elements[5].attributes.size ).to eq 1
expect( xml_doc.elements[1].attributes['attr1'] ).to eq 'val1'
expect( xml_doc.elements[2].attributes['attr2'] ).to be nil
expect( xml_doc.elements[3].attributes['attr3'] ).to eq 'val3'
expect( xml_doc.elements[4].attributes['attr4'] ).to be nil
expect( xml_doc.elements[5].attributes['attr5'] ).to eq 'val5'
end
end
end
describe "when instantiated with XML string and context" do
let(:xml_doc){ described_class.new xml_str, context }
let(:xml_str){ " <root1>\n <dummy1 />\n </root1>\n " }
describe "when context is empty" do
let(:context){ {} }
it "contains whitespace text nodes" do
expect( xml_doc.children.first.class ).to eq REXML::Text
expect( xml_doc.children.first.value ).to eq " "
expect( xml_doc.children.last.class ).to eq REXML::Text
expect( xml_doc.children.last.value ).to eq "\n "
expect( xml_doc.elements['root1'].children.first.class ).to eq REXML::Text
expect( xml_doc.elements['root1'].children.first.value ).to eq "\n "
expect( xml_doc.elements['root1'].children.last.class ).to eq REXML::Text
expect( xml_doc.elements['root1'].children.last.value ).to eq "\n "
end
end
describe "when context is {:ignore_whitespace_nodes => :all}" do
let(:context){ {:ignore_whitespace_nodes => :all} }
it "doesn't contain whitespace text nodes" do
expect( xml_doc.children.first.class ).to eq REXML::Element
expect( xml_doc.children.first.name ).to eq "root1"
expect( xml_doc.children.last.class ).to eq REXML::Element
expect( xml_doc.children.last.name ).to eq "root1"
expect( xml_doc.elements['root1'].children.first.class ).to eq REXML::Element
expect( xml_doc.elements['root1'].children.first.name ).to eq "dummy1"
expect( xml_doc.elements['root1'].children.last.class ).to eq REXML::Element
expect( xml_doc.elements['root1'].children.last.name ).to eq "dummy1"
end
end
end
describe "when #clone method is called" do
let(:xml_doc){ described_class.new xml_str }
let(:xml_str){
<<-EOB
<root attr1="val1">
<dummy1 />
</root>
<root>
<dummy2 />
</root>
<root attr3="val3">
<dummy3 />
</root>
EOB
}
context "#clone" do
let(:xml_doc_clone){ xml_doc.clone }
it "returns HrrRbRelaxedXML::Document instance" do
expect( xml_doc_clone ).to be_instance_of described_class
end
end
context "#deep_clone" do
let(:xml_doc_deep_clone){ xml_doc.deep_clone }
it "returns HrrRbRelaxedXML::Document instance" do
expect( xml_doc_deep_clone ).to be_instance_of described_class
end
it "returns deeply cloned multiple elements " do
expect( xml_doc_deep_clone.elements.size ).to eq 3
expect( xml_doc_deep_clone.elements[1].name ).to eq 'root'
expect( xml_doc_deep_clone.elements[2].name ).to eq 'root'
expect( xml_doc_deep_clone.elements[3].name ).to eq 'root'
expect( xml_doc_deep_clone.elements[1].attributes.size ).to eq 1
expect( xml_doc_deep_clone.elements[2].attributes.size ).to eq 0
expect( xml_doc_deep_clone.elements[3].attributes.size ).to eq 1
expect( xml_doc_deep_clone.elements[1].attributes['attr1'] ).to eq 'val1'
expect( xml_doc_deep_clone.elements[2].attributes['attr2'] ).to be nil
expect( xml_doc_deep_clone.elements[3].attributes['attr3'] ).to eq 'val3'
expect( xml_doc_deep_clone.elements[1].elements.size ).to eq 1
expect( xml_doc_deep_clone.elements[2].elements.size ).to eq 1
expect( xml_doc_deep_clone.elements[3].elements.size ).to eq 1
expect( xml_doc_deep_clone.elements[1].elements[1].name ).to eq 'dummy1'
expect( xml_doc_deep_clone.elements[2].elements[1].name ).to eq 'dummy2'
expect( xml_doc_deep_clone.elements[3].elements[1].name ).to eq 'dummy3'
end
end
end
describe "when #root method is called" do
let(:xml_doc){ described_class.new xml_str }
let(:xml_str){
<<-EOB
<root1 attr1="val1">
<dummy1 />
</root1>
<root2>
<dummy2 />
</root2>
<root3 attr3="val3">
<dummy3 />
</root3>
EOB
}
describe "when current context is a descendant of first root element" do
let(:context_e){ xml_doc.elements['root1'].elements['dummy1'] }
it "returns the context element's root node" do
expect( context_e.root.name ).to eq "root1"
end
end
describe "when current context is a descendant of second root element" do
let(:context_e){ xml_doc.elements['root2'].elements['dummy2'] }
it "returns the context element's root node" do
expect( context_e.root.name ).to eq "root2"
end
end
describe "when current context is a descendant of last root element" do
let(:context_e){ xml_doc.elements['root3'].elements['dummy3'] }
it "returns the context element's root node" do
expect( context_e.root.name ).to eq "root3"
end
end
end
describe "when #xpath method is called" do
let(:xml_doc){ described_class.new xml_str }
let(:xml_str){
<<-EOB
<root attr1="val1">
<dummy1 />
</root>
<root>
<dummy2 />
</root>
<root attr3="val3">
<dummy3 />
</root>
EOB
}
let(:root1_xpath){ xml_doc.elements[1].xpath }
let(:root2_xpath){ xml_doc.elements[2].xpath }
let(:root3_xpath){ xml_doc.elements[3].xpath }
it "differentiate each root element" do
expect( root1_xpath ).to_not eq root2_xpath
expect( root2_xpath ).to_not eq root3_xpath
expect( root3_xpath ).to_not eq root1_xpath
end
end
end
| 41.172956 | 92 | 0.609753 |
018a74083f54390824dc7cf1adc44dde59f7db88 | 406 | # Sample code from Programing Ruby, page 106
@esmtp = true
begin
# First try an extended login. If it fails because the
# server doesn't support it, fall back to a normal login
if @esmtp then
@command.ehlo(helodom)
else
@command.helo(helodom)
end
rescue ProtocolError
if @esmtp then
@esmtp = false
retry
else
raise
end
end
| 18.454545 | 60 | 0.610837 |
629e6f8d4854dc6b2eb023a9bfd3c37db20a3dba | 5,778 | # -------------------------------------------------------------------------- #
# Copyright 2002-2018, OpenNebula Project, OpenNebula Systems #
# #
# 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. #
#--------------------------------------------------------------------------- #
if !ONE_LOCATION
LOG_LOCATION = "/var/log/one"
else
LOG_LOCATION = ONE_LOCATION + "/var"
end
LOG = LOG_LOCATION + "/onedb-vcenter-one54.log"
TMP_DIR = "/var/tmp/vcenter_one54"
module One54Vcenter
VERSION = "5.4.0"
def check_db_version(ops)
db_version = read_db_version()
if ( db_version[:version] != VERSION )
raise <<-EOT
Version mismatch: vcenter migration is for version #{VERSION}
Current database is version #{db_version[:version]}
EOT
end
end
def migrate_templates(verbose)
Dir["#{TMP_DIR}/one_migrate_template_*"].each do |template_filename|
template_id = template_filename.split("_")[-1]
template_xml = File.read(template_filename)
@db.run("UPDATE template_pool SET body='#{template_xml}' WHERE oid='#{template_id}'")
puts " Template #{template_id} migrated!" if verbose
end
return true
end
def migrate_vms(verbose)
Dir["#{TMP_DIR}/one_migrate_vm_*"].each do |vm_filename|
vm_id = vm_filename.split("_")[-1]
vm_xml = File.read(vm_filename)
vm_xml_doc = REXML::Document.new(vm_xml).root
seq_node = vm_xml_doc.elements["HISTORY_RECORDS/HISTORY/SEQ"]
dsid_node = vm_xml_doc.elements["HISTORY_RECORDS/HISTORY/DS_ID"]
if seq_node && seq_node.has_text? && dsid_node && dsid_node.has_text?
seq = seq_node.text
dsid= dsid_node.text
begin
h_dataset = @db["SELECT body from history where vid=#{vm_id} and seq=#{seq}"]
h_body = h_dataset.map(:body)
h_xml = REXML::Document.new(h_body[0]).root
h_ds_node = h_xml.elements["DS_ID"]
if h_ds_node && h_ds_node.has_text?
h_ds_node.text = dsid
h_xml.delete_element "TM_MAD"
tmmad_elem = REXML::Element.new("TM_MAD")
tmmad_elem.text = "vcenter"
h_xml.add_element(tmmad_elem)
@db.run("UPDATE history SET body='#{h_xml.to_s}' WHERE vid=#{vm_id} and seq=#{seq}")
end
rescue
puts "VM #{vm_id} cannot set datastore. Manual update needed"
end
end
@db.run("UPDATE vm_pool SET body='#{vm_xml}' WHERE oid='#{vm_id}'")
puts " VM #{vm_id} migrated!" if verbose
end
return true
end
def migrate_hosts(verbose)
Dir["#{TMP_DIR}/one_migrate_host_*"].each do |host_filename|
host_id = host_filename.split("_")[-1]
host_xml = File.read(host_filename)
@db.run("UPDATE host_pool SET body='#{host_xml}' WHERE oid='#{host_id}'")
puts " Host #{host_id} migrated!" if verbose
end
return true
end
def migrate_datastores(verbose)
Dir["#{TMP_DIR}/one_migrate_ds_*"].each do |ds_filename|
ds_id = ds_filename.split("_")[-1]
ds_xml = File.read(ds_filename)
@db.run("UPDATE datastore_pool SET body='#{ds_xml}' WHERE oid='#{ds_id}'")
puts " Datastore #{ds_id} migrated!" if verbose
end
return true
end
def migrate_vnets(verbose)
Dir["#{TMP_DIR}/one_migrate_vnet_*"].each do |vnet_filename|
vnet_id = vnet_filename.split("_")[-1]
vnet_xml = File.read(vnet_filename)
@db.run("UPDATE network_pool SET body='#{vnet_xml}' WHERE oid='#{vnet_id}'")
puts " Network #{vnet_id} migrated!" if verbose
end
return true
end
def migrate_images(verbose)
Dir["#{TMP_DIR}/one_migrate_image_*"].each do |image_filename|
image_id = image_filename.split("_")[-1]
image_xml = File.read(image_filename)
@db.run("UPDATE image_pool SET body='#{image_xml}' WHERE oid='#{image_id}'")
puts " Image #{image_id} migrated!" if verbose
end
return true
end
def migrate_history(verbose)
Dir["#{TMP_DIR}/one_migrate_history_*"].each do |history_filename|
vm_id = history_filename.split("_")[-2]
seq_id = history_filename.split("_")[-1]
history_xml = File.read(history_filename)
@db.run("UPDATE history SET body='#{history_xml}' WHERE vid='#{vm_id}' and seq='#{seq_id}'")
puts " History for VM #{vm_id} migrated!" if verbose
end
return true
end
end
| 37.277419 | 104 | 0.536691 |
79cd034f875fa8dc7a12305c078e4b5b3a24ae23 | 128 | require 'test_helper'
class QuestionOptionTest < ActiveSupport::TestCase
# test "the truth" do
# assert true
# end
end
| 16 | 50 | 0.71875 |
28d78bc9556ed108b3dda646b35ae0fc44c277e8 | 714 | $:.unshift File.join(File.dirname(__FILE__), 'lib')
require 'erb2rux/version'
Gem::Specification.new do |s|
s.name = 'erb2rux'
s.version = ::Erb2Rux::VERSION
s.authors = ['Cameron Dutro']
s.email = ['[email protected]']
s.homepage = 'http://github.com/camertron/erb2rux'
s.description = s.summary = 'Automatically convert .html.erb files into .rux files.'
s.platform = Gem::Platform::RUBY
s.add_dependency 'actionview', '~> 6.1'
s.add_dependency 'parser', '~> 3.0'
s.add_dependency 'unparser', '~> 0.6'
s.require_path = 'lib'
s.executables << 'erb2rux'
s.files = Dir['{lib,spec}/**/*', 'Gemfile', 'LICENSE', 'CHANGELOG.md', 'README.md', 'Rakefile', 'erb2rux.gemspec']
end
| 31.043478 | 116 | 0.654062 |
03806111083302bde5e1380bf49d8873e85c5c63 | 31 | class Refund < Transaction
end
| 10.333333 | 26 | 0.806452 |
0841fca2e1e07610833d0ad17cb560c1d23d7a44 | 285 | module Aspellbee
module Middleware
# Check if the client has set-up configuration yet.
class InjectConfiguration < Base
def call(env)
config = Aspellbee::Configuration.instance
env['config'] = config
@app.call(env)
end
end
end
end
| 19 | 55 | 0.638596 |
1c94d9bf6eb328809b8d2da5e71dd339c53de7a5 | 76 | Mutest::Meta::Example.add :gvar do
source '$a'
singleton_mutations
end
| 12.666667 | 34 | 0.723684 |
395ebe209594cfe300d6a03feb46af2981e99255 | 916 | require 'rails_helper'
describe Level do
context '.validates' do
it { should validate_numericality_of(:required_score).only_integer }
it { should validate_uniqueness_of(:name) }
end
describe '.by_score(score)' do
before { create(:level) }
it 'should find level by pontution' do
expect(Level.first_by_score(100).id).to eq(Level.first.id)
end
end
describe '.order_by_required' do
before do
create(:level)
create(:level, required_score: 30)
end
it 'should find level by order' do
expect(Level.order_by_required.first.id).to eq(Level.first.id)
end
end
describe '.first_by_score' do
let!(:level) { create(:level, required_score: 70) }
before do
create(:level)
create(:level, required_score: 71)
end
it 'should find level by first score' do
expect(Level.first_by_score(70)).to eq(level)
end
end
end
| 21.809524 | 72 | 0.668122 |
87513e18b25a7b31b304af56e26c7e7d398093a6 | 18,241 | require 'spec_helper'
describe Member do
describe "Associations" do
it { is_expected.to belong_to(:user) }
end
describe "Validation" do
subject { described_class.new(access_level: Member::GUEST) }
it { is_expected.to validate_presence_of(:user) }
it { is_expected.to validate_presence_of(:source) }
it { is_expected.to validate_inclusion_of(:access_level).in_array(Gitlab::Access.all_values) }
it_behaves_like 'an object with email-formated attributes', :invite_email do
subject { build(:project_member) }
end
context "when an invite email is provided" do
let(:member) { build(:project_member, invite_email: "[email protected]", user: nil) }
it "doesn't require a user" do
expect(member).to be_valid
end
it "requires a valid invite email" do
member.invite_email = "nope"
expect(member).not_to be_valid
end
it "requires a unique invite email scoped to this source" do
create(:project_member, source: member.source, invite_email: member.invite_email)
expect(member).not_to be_valid
end
it "is valid otherwise" do
expect(member).to be_valid
end
end
context "when an invite email is not provided" do
let(:member) { build(:project_member) }
it "requires a user" do
member.user = nil
expect(member).not_to be_valid
end
it "is valid otherwise" do
expect(member).to be_valid
end
end
end
describe 'Scopes & finders' do
before do
project = create(:project, :public, :access_requestable)
group = create(:group)
@owner_user = create(:user).tap { |u| group.add_owner(u) }
@owner = group.members.find_by(user_id: @owner_user.id)
@master_user = create(:user).tap { |u| project.team << [u, :master] }
@master = project.members.find_by(user_id: @master_user.id)
@blocked_user = create(:user).tap do |u|
project.team << [u, :master]
project.team << [u, :developer]
u.block!
end
@blocked_master = project.members.find_by(user_id: @blocked_user.id, access_level: Gitlab::Access::MASTER)
@blocked_developer = project.members.find_by(user_id: @blocked_user.id, access_level: Gitlab::Access::DEVELOPER)
@invited_member = create(:project_member, :developer,
project: project,
invite_token: '1234',
invite_email: '[email protected]')
accepted_invite_user = build(:user, state: :active)
@accepted_invite_member = create(:project_member, :developer,
project: project,
invite_token: '1234',
invite_email: '[email protected]')
.tap { |u| u.accept_invite!(accepted_invite_user) }
requested_user = create(:user).tap { |u| project.request_access(u) }
@requested_member = project.requesters.find_by(user_id: requested_user.id)
accepted_request_user = create(:user).tap { |u| project.request_access(u) }
@accepted_request_member = project.requesters.find_by(user_id: accepted_request_user.id).tap { |m| m.accept_request }
end
describe '.access_for_user_ids' do
it 'returns the right access levels' do
users = [@owner_user.id, @master_user.id, @blocked_user.id]
expected = {
@owner_user.id => Gitlab::Access::OWNER,
@master_user.id => Gitlab::Access::MASTER
}
expect(described_class.access_for_user_ids(users)).to eq(expected)
end
end
describe '.invite' do
it { expect(described_class.invite).not_to include @master }
it { expect(described_class.invite).to include @invited_member }
it { expect(described_class.invite).not_to include @accepted_invite_member }
it { expect(described_class.invite).not_to include @requested_member }
it { expect(described_class.invite).not_to include @accepted_request_member }
end
describe '.non_invite' do
it { expect(described_class.non_invite).to include @master }
it { expect(described_class.non_invite).not_to include @invited_member }
it { expect(described_class.non_invite).to include @accepted_invite_member }
it { expect(described_class.non_invite).to include @requested_member }
it { expect(described_class.non_invite).to include @accepted_request_member }
end
describe '.request' do
it { expect(described_class.request).not_to include @master }
it { expect(described_class.request).not_to include @invited_member }
it { expect(described_class.request).not_to include @accepted_invite_member }
it { expect(described_class.request).to include @requested_member }
it { expect(described_class.request).not_to include @accepted_request_member }
end
describe '.non_request' do
it { expect(described_class.non_request).to include @master }
it { expect(described_class.non_request).to include @invited_member }
it { expect(described_class.non_request).to include @accepted_invite_member }
it { expect(described_class.non_request).not_to include @requested_member }
it { expect(described_class.non_request).to include @accepted_request_member }
end
describe '.developers' do
subject { described_class.developers.to_a }
it { is_expected.not_to include @owner }
it { is_expected.not_to include @master }
it { is_expected.to include @invited_member }
it { is_expected.to include @accepted_invite_member }
it { is_expected.not_to include @requested_member }
it { is_expected.to include @accepted_request_member }
it { is_expected.not_to include @blocked_master }
it { is_expected.not_to include @blocked_developer }
end
describe '.owners_and_masters' do
it { expect(described_class.owners_and_masters).to include @owner }
it { expect(described_class.owners_and_masters).to include @master }
it { expect(described_class.owners_and_masters).not_to include @invited_member }
it { expect(described_class.owners_and_masters).not_to include @accepted_invite_member }
it { expect(described_class.owners_and_masters).not_to include @requested_member }
it { expect(described_class.owners_and_masters).not_to include @accepted_request_member }
it { expect(described_class.owners_and_masters).not_to include @blocked_master }
end
describe '.has_access' do
subject { described_class.has_access.to_a }
it { is_expected.to include @owner }
it { is_expected.to include @master }
it { is_expected.to include @invited_member }
it { is_expected.to include @accepted_invite_member }
it { is_expected.not_to include @requested_member }
it { is_expected.to include @accepted_request_member }
it { is_expected.not_to include @blocked_master }
it { is_expected.not_to include @blocked_developer }
end
end
describe "Delegate methods" do
it { is_expected.to respond_to(:user_name) }
it { is_expected.to respond_to(:user_email) }
end
describe '.add_user' do
%w[project group].each do |source_type|
context "when source is a #{source_type}" do
let!(:source) { create(source_type, :public, :access_requestable) }
let!(:user) { create(:user) }
let!(:admin) { create(:admin) }
it 'returns a <Source>Member object' do
member = described_class.add_user(source, user, :master)
expect(member).to be_a "#{source_type.classify}Member".constantize
expect(member).to be_persisted
end
it 'sets members.created_by to the given current_user' do
member = described_class.add_user(source, user, :master, current_user: admin)
expect(member.created_by).to eq(admin)
end
it 'sets members.expires_at to the given expires_at' do
member = described_class.add_user(source, user, :master, expires_at: Date.new(2016, 9, 22))
expect(member.expires_at).to eq(Date.new(2016, 9, 22))
end
described_class.access_levels.each do |sym_key, int_access_level|
it "accepts the :#{sym_key} symbol as access level" do
expect(source.users).not_to include(user)
member = described_class.add_user(source, user.id, sym_key)
expect(member.access_level).to eq(int_access_level)
expect(source.users.reload).to include(user)
end
it "accepts the #{int_access_level} integer as access level" do
expect(source.users).not_to include(user)
member = described_class.add_user(source, user.id, int_access_level)
expect(member.access_level).to eq(int_access_level)
expect(source.users.reload).to include(user)
end
end
context 'with no current_user' do
context 'when called with a known user id' do
it 'adds the user as a member' do
expect(source.users).not_to include(user)
described_class.add_user(source, user.id, :master)
expect(source.users.reload).to include(user)
end
end
context 'when called with an unknown user id' do
it 'adds the user as a member' do
expect(source.users).not_to include(user)
described_class.add_user(source, 42, :master)
expect(source.users.reload).not_to include(user)
end
end
context 'when called with a user object' do
it 'adds the user as a member' do
expect(source.users).not_to include(user)
described_class.add_user(source, user, :master)
expect(source.users.reload).to include(user)
end
end
context 'when called with a requester user object' do
before do
source.request_access(user)
end
it 'adds the requester as a member' do
expect(source.users).not_to include(user)
expect(source.requesters.exists?(user_id: user)).to be_truthy
expect { described_class.add_user(source, user, :master) }
.to raise_error(Gitlab::Access::AccessDeniedError)
expect(source.users.reload).not_to include(user)
expect(source.requesters.reload.exists?(user_id: user)).to be_truthy
end
end
context 'when called with a known user email' do
it 'adds the user as a member' do
expect(source.users).not_to include(user)
described_class.add_user(source, user.email, :master)
expect(source.users.reload).to include(user)
end
end
context 'when called with an unknown user email' do
it 'creates an invited member' do
expect(source.users).not_to include(user)
described_class.add_user(source, '[email protected]', :master)
expect(source.members.invite.pluck(:invite_email)).to include('[email protected]')
end
end
end
context 'when current_user can update member' do
it 'creates the member' do
expect(source.users).not_to include(user)
described_class.add_user(source, user, :master, current_user: admin)
expect(source.users.reload).to include(user)
end
context 'when called with a requester user object' do
before do
source.request_access(user)
end
it 'adds the requester as a member' do
expect(source.users).not_to include(user)
expect(source.requesters.exists?(user_id: user)).to be_truthy
described_class.add_user(source, user, :master, current_user: admin)
expect(source.users.reload).to include(user)
expect(source.requesters.reload.exists?(user_id: user)).to be_falsy
end
end
end
context 'when current_user cannot update member' do
it 'does not create the member' do
expect(source.users).not_to include(user)
member = described_class.add_user(source, user, :master, current_user: user)
expect(source.users.reload).not_to include(user)
expect(member).not_to be_persisted
end
context 'when called with a requester user object' do
before do
source.request_access(user)
end
it 'does not destroy the requester' do
expect(source.users).not_to include(user)
expect(source.requesters.exists?(user_id: user)).to be_truthy
described_class.add_user(source, user, :master, current_user: user)
expect(source.users.reload).not_to include(user)
expect(source.requesters.exists?(user_id: user)).to be_truthy
end
end
end
context 'when member already exists' do
before do
source.add_user(user, :developer)
end
context 'with no current_user' do
it 'updates the member' do
expect(source.users).to include(user)
described_class.add_user(source, user, :master)
expect(source.members.find_by(user_id: user).access_level).to eq(Gitlab::Access::MASTER)
end
end
context 'when current_user can update member' do
it 'updates the member' do
expect(source.users).to include(user)
described_class.add_user(source, user, :master, current_user: admin)
expect(source.members.find_by(user_id: user).access_level).to eq(Gitlab::Access::MASTER)
end
end
context 'when current_user cannot update member' do
it 'does not update the member' do
expect(source.users).to include(user)
described_class.add_user(source, user, :master, current_user: user)
expect(source.members.find_by(user_id: user).access_level).to eq(Gitlab::Access::DEVELOPER)
end
end
end
end
end
end
describe '.add_users' do
%w[project group].each do |source_type|
context "when source is a #{source_type}" do
let!(:source) { create(source_type, :public, :access_requestable) }
let!(:admin) { create(:admin) }
let(:user1) { create(:user) }
let(:user2) { create(:user) }
it 'returns a <Source>Member objects' do
members = described_class.add_users(source, [user1, user2], :master)
expect(members).to be_a Array
expect(members.size).to eq(2)
expect(members.first).to be_a "#{source_type.classify}Member".constantize
expect(members.first).to be_persisted
end
it 'returns an empty array' do
members = described_class.add_users(source, [], :master)
expect(members).to be_a Array
expect(members).to be_empty
end
end
end
end
describe '#accept_request' do
let(:member) { create(:project_member, requested_at: Time.now.utc) }
it { expect(member.accept_request).to be_truthy }
it 'clears requested_at' do
member.accept_request
expect(member.requested_at).to be_nil
end
it 'calls #after_accept_request' do
expect(member).to receive(:after_accept_request)
member.accept_request
end
end
describe '#invite?' do
subject { create(:project_member, invite_email: "[email protected]", user: nil) }
it { is_expected.to be_invite }
end
describe '#request?' do
subject { create(:project_member, requested_at: Time.now.utc) }
it { is_expected.to be_request }
end
describe '#pending?' do
let(:invited_member) { create(:project_member, invite_email: "[email protected]", user: nil) }
let(:requester) { create(:project_member, requested_at: Time.now.utc) }
it { expect(invited_member).to be_invite }
it { expect(requester).to be_pending }
end
describe "#accept_invite!" do
let!(:member) { create(:project_member, invite_email: "[email protected]", user: nil) }
let(:user) { create(:user) }
it "resets the invite token" do
member.accept_invite!(user)
expect(member.invite_token).to be_nil
end
it "sets the invite accepted timestamp" do
member.accept_invite!(user)
expect(member.invite_accepted_at).not_to be_nil
end
it "sets the user" do
member.accept_invite!(user)
expect(member.user).to eq(user)
end
it "calls #after_accept_invite" do
expect(member).to receive(:after_accept_invite)
member.accept_invite!(user)
end
it "refreshes user's authorized projects", truncate: true do
project = member.source
expect(user.authorized_projects).not_to include(project)
member.accept_invite!(user)
expect(user.authorized_projects.reload).to include(project)
end
end
describe "#decline_invite!" do
let!(:member) { create(:project_member, invite_email: "[email protected]", user: nil) }
it "destroys the member" do
member.decline_invite!
expect(member).to be_destroyed
end
it "calls #after_decline_invite" do
expect(member).to receive(:after_decline_invite)
member.decline_invite!
end
end
describe "#generate_invite_token" do
let!(:member) { create(:project_member, invite_email: "[email protected]", user: nil) }
it "sets the invite token" do
expect { member.generate_invite_token }.to change { member.invite_token}
end
end
describe "destroying a record", truncate: true do
it "refreshes user's authorized projects" do
project = create(:project, :private)
user = create(:user)
member = project.team << [user, :reporter]
member.destroy
expect(user.authorized_projects).not_to include(project)
end
end
end
| 34.482042 | 123 | 0.642838 |
01aa44f5fc1c252ec92fdc8bf1fd969a1d7b7e12 | 124 | class AddGithubIdToIssues < ActiveRecord::Migration[6.0]
def change
add_column :issues, :github_id, :bigint
end
end
| 20.666667 | 56 | 0.75 |
e8983d6e6795b0853b397e54abe68d0a2e1f7855 | 773 | class DropTablesForActsAsTaggable < ActiveRecord::Migration[6.0]
def up
drop_table :taggings
drop_table :tags
end
def down
create_table "taggings" do |t|
t.integer "tag_id"
t.integer "taggable_id"
t.string "taggable_type"
t.integer "tagger_id"
t.string "tagger_type"
t.string "context", limit: 128
t.datetime "created_at"
end
add_index "taggings", ["tag_id", "taggable_id", "taggable_type", "context", "tagger_id", "tagger_type"], name: "taggings_idx", unique: true, using: :btree
create_table "tags" do |t|
t.string "name"
t.integer "taggings_count", default: 0
end
add_index "tags", ["name"], name: "index_tags_on_name", unique: true, using: :btree
end
end
| 27.607143 | 158 | 0.640362 |
39d2a8ceed6729df0c24a0cfbe74ac7c08e84b7c | 69 | class Tag < ApplicationRecord
has_and_belongs_to_many :gossips
end
| 17.25 | 34 | 0.84058 |
b9d19246d9e87e2e4744340d9a9e525d2f3a637e | 180 | module Arelastic
module Aggregations
class Min < Arelastic::Aggregations::Aggregation
def as_elastic_aggregation
{'min' => options}
end
end
end
end
| 18 | 52 | 0.666667 |
18ff99f7bbc0154bc2a78d4ba17d46f2ff66d83e | 864 | class StripePayout < StripeModelCallbacks::ApplicationRecord
monetize :amount_cents, allow_nil: true
def self.stripe_class
Stripe::Payout
end
def assign_from_stripe(object)
check_object_is_stripe_class(object)
assign_attributes(
amount: Money.new(object.amount, object.currency),
arrival_date: Time.zone.at(object.arrival_date),
created: Time.zone.at(object.created),
metadata: JSON.generate(object.metadata),
stripe_method: object.method,
stripe_type: object.type
)
StripeModelCallbacks::AttributesAssignerService.execute!(
model: self, stripe_model: object,
attributes: %w[
automatic balance_transaction currency description destination failure_balance_transaction
failure_code failure_message livemode source_type statement_descriptor status
]
)
end
end
| 30.857143 | 98 | 0.743056 |
2100ff5133a0257aa1c96a9c3ad6401fe4f5300d | 1,894 | require 'json'
module KegbotApi
# Encapsulates a REST response ({Net::HTTPResponse})
#
# @visibility private
class RestResponse
# HTTP status code returned
attr_accessor :status_code
# result (as a string)
attr_accessor :body
# result (parsed into a {Hash})
attr_accessor :body_hash
# @overload initialize(http_response)
# @param http_reponse [Net::HTTPResponse]
def initialize(*args)
http_response = args.slice!(0)
self.status_code = http_response.code.to_i
self.body = http_response.read_body
end
def success?
self.status_code == 200 && self.meta_result == 'ok'
end
# Raises an instance of {KegbotApi::Error} appropriate to the error code returned in the response
def raise_arguments
error_name = self.error_code
klass = KegbotApi.const_defined?(error_name) ? KegbotApi.const_get(error_name) : KegbotApi::Error
[klass, self.error_message]
end
# Parses the http result body into a {Hash}
def body_hash
@body_hash ||= JSON::load(self.body)
end
def metadata
hash_attribute_or_fail(self.body_hash, 'meta')
end
def meta_result
hash_attribute_or_fail(self.metadata, 'result')
end
def error
hash_attribute_or_fail(self.body_hash, 'error')
end
def error_code
hash_attribute_or_fail(self.error, 'code')
end
def error_message
hash_attribute_or_fail(self.error, 'message')
self.error['message']
end
def objects
hash_attribute_or_fail(self.body_hash, 'objects')
end
def object
hash_attribute_or_fail(self.body_hash, 'object')
end
def hash_attribute_or_fail(hash, attribute)
(found = hash[attribute]) ? found : raise(InvalidInputError, "Server JSON response didn't include the expected '#{attribute}' field. #{hash.inspect}")
end
end
end | 24.921053 | 157 | 0.680042 |
abc3424ac5f35062433180ee490e308c2bc3796b | 670 | require 'test_helper'
class MicropostTest < ActiveSupport::TestCase
def setup
@user = users(:michael)
@micropost = @user.microposts.build(content: 'Lorem ipsum')
end
test "should be valid" do
assert @micropost.valid?
end
test "user id should be present" do
@micropost.user_id = nil
assert_not @micropost.valid?
end
test "content should be present" do
@micropost.content = " "
assert_not @micropost.valid?
end
test "content should be at most 140 characters" do
@micropost.content = "a" * 141
assert_not @micropost.valid?
end
test "order should be most recent first" do
assert_equal microposts(:most_recent), Micropost.first
end
end
| 20.30303 | 61 | 0.729851 |
edfd2870bfe7e8864973a9a74ee73d945f5b1a97 | 1,233 | # coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'PS2Format/version'
Gem::Specification.new do |spec|
spec.name = "PS2Format"
spec.version = PS2Format::VERSION
spec.authors = ["Runtime Revolution"]
spec.summary = %q{PS2 provides you the ability of creating PS2 type files used to make financial transfers with a bank.}
spec.description = %q{PS2 provides you the ability of creating PS2 type files used to make financial transfers with a bank.}
spec.license = "MIT"
spec.homepage = "https://github.com/runtimerevolution/ps2"
spec.email = '[email protected]'
spec.files = Dir["{lib}/**/*"]
spec.bindir = "exe"
spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
spec.require_paths = ["lib"]
spec.add_dependency "i18n", "~> 0.7.0"
spec.add_dependency "citizenship", "~> 1.0"
spec.add_development_dependency 'coveralls'
spec.add_development_dependency 'simplecov'
spec.add_development_dependency "bundler", "~> 1.3"
spec.add_development_dependency "rake", "~> 10.0"
spec.add_development_dependency "test-unit", "~> 3.1.2"
end
| 39.774194 | 128 | 0.679643 |
f7e8eb5d3bac790c06585c79b3d7e96d6207f675 | 238 | # frozen_string_literal: true
i = 0
json.array! @article.revisions.each do |revision|
i += 1
json.index i
json.rev_id revision.mw_rev_id
json.wp10 revision.wp10
json.date revision.date
json.username revision.user.username
end
| 21.636364 | 49 | 0.756303 |
4ac59aa2dac1d2760261de117354f2917f319133 | 2,009 | require "rodauth/rails/version"
require "rodauth/rails/railtie"
module Rodauth
module Rails
class Error < StandardError
end
# This allows the developer to avoid loading Rodauth at boot time.
autoload :App, "rodauth/rails/app"
autoload :Auth, "rodauth/rails/auth"
@app = nil
@middleware = true
class << self
def rodauth(name = nil)
url_options = ActionMailer::Base.default_url_options
scheme = url_options[:protocol] || "http"
port = url_options[:port]
port ||= Rack::Request::DEFAULT_PORTS[scheme] if Gem::Version.new(Rack.release) < Gem::Version.new("2.0")
host = url_options[:host]
host += ":#{port}" if port
rack_env = {
"HTTP_HOST" => host,
"rack.url_scheme" => scheme,
}
scope = app.new(rack_env)
scope.rodauth(name)
end
# routing constraint that requires authentication
def authenticated(name = nil, &condition)
lambda do |request|
rodauth = request.env.fetch ["rodauth", *name].join(".")
rodauth.require_authentication
rodauth.authenticated? && (condition.nil? || condition.call(rodauth))
end
end
if ::Rails.gem_version >= Gem::Version.new("5.2")
def secret_key_base
::Rails.application.secret_key_base
end
else
def secret_key_base
::Rails.application.secrets.secret_key_base
end
end
if ::Rails.gem_version >= Gem::Version.new("5.0")
def api_only?
::Rails.application.config.api_only
end
else
def api_only?
false
end
end
def configure
yield self
end
attr_writer :app
attr_writer :middleware
def app
fail Rodauth::Rails::Error, "app was not configured" unless @app
@app.constantize
end
def middleware?
@middleware
end
end
end
end
| 23.916667 | 115 | 0.582379 |
01e90a4f0ddba459cb859ad54b78a5349b3ab16f | 106,230 | # frozen_string_literal: true
require "cgi"
require "action_view/helpers/date_helper"
require "action_view/helpers/tag_helper"
require "action_view/helpers/form_tag_helper"
require "action_view/helpers/active_model_helper"
require "action_view/model_naming"
require "action_view/record_identifier"
require "active_support/core_ext/module/attribute_accessors"
require "active_support/core_ext/hash/slice"
require "active_support/core_ext/string/output_safety"
require "active_support/core_ext/string/inflections"
module ActionView
# = Action View Form Helpers
module Helpers #:nodoc:
# Form helpers are designed to make working with resources much easier
# compared to using vanilla HTML.
#
# Typically, a form designed to create or update a resource reflects the
# identity of the resource in several ways: (i) the URL that the form is
# sent to (the form element's +action+ attribute) should result in a request
# being routed to the appropriate controller action (with the appropriate <tt>:id</tt>
# parameter in the case of an existing resource), (ii) input fields should
# be named in such a way that in the controller their values appear in the
# appropriate places within the +params+ hash, and (iii) for an existing record,
# when the form is initially displayed, input fields corresponding to attributes
# of the resource should show the current values of those attributes.
#
# In Rails, this is usually achieved by creating the form using +form_for+ and
# a number of related helper methods. +form_for+ generates an appropriate <tt>form</tt>
# tag and yields a form builder object that knows the model the form is about.
# Input fields are created by calling methods defined on the form builder, which
# means they are able to generate the appropriate names and default values
# corresponding to the model attributes, as well as convenient IDs, etc.
# Conventions in the generated field names allow controllers to receive form data
# nicely structured in +params+ with no effort on your side.
#
# For example, to create a new person you typically set up a new instance of
# +Person+ in the <tt>PeopleController#new</tt> action, <tt>@person</tt>, and
# in the view template pass that object to +form_for+:
#
# <%= form_for @person do |f| %>
# <%= f.label :first_name %>:
# <%= f.text_field :first_name %><br />
#
# <%= f.label :last_name %>:
# <%= f.text_field :last_name %><br />
#
# <%= f.submit %>
# <% end %>
#
# The HTML generated for this would be (modulus formatting):
#
# <form action="/people" class="new_person" id="new_person" method="post">
# <input name="authenticity_token" type="hidden" value="NrOp5bsjoLRuK8IW5+dQEYjKGUJDe7TQoZVvq95Wteg=" />
# <label for="person_first_name">First name</label>:
# <input id="person_first_name" name="person[first_name]" type="text" /><br />
#
# <label for="person_last_name">Last name</label>:
# <input id="person_last_name" name="person[last_name]" type="text" /><br />
#
# <input name="commit" type="submit" value="Create Person" />
# </form>
#
# As you see, the HTML reflects knowledge about the resource in several spots,
# like the path the form should be submitted to, or the names of the input fields.
#
# In particular, thanks to the conventions followed in the generated field names, the
# controller gets a nested hash <tt>params[:person]</tt> with the person attributes
# set in the form. That hash is ready to be passed to <tt>Person.new</tt>:
#
# @person = Person.new(params[:person])
# if @person.save
# # success
# else
# # error handling
# end
#
# Interestingly, the exact same view code in the previous example can be used to edit
# a person. If <tt>@person</tt> is an existing record with name "John Smith" and ID 256,
# the code above as is would yield instead:
#
# <form action="/people/256" class="edit_person" id="edit_person_256" method="post">
# <input name="_method" type="hidden" value="patch" />
# <input name="authenticity_token" type="hidden" value="NrOp5bsjoLRuK8IW5+dQEYjKGUJDe7TQoZVvq95Wteg=" />
# <label for="person_first_name">First name</label>:
# <input id="person_first_name" name="person[first_name]" type="text" value="John" /><br />
#
# <label for="person_last_name">Last name</label>:
# <input id="person_last_name" name="person[last_name]" type="text" value="Smith" /><br />
#
# <input name="commit" type="submit" value="Update Person" />
# </form>
#
# Note that the endpoint, default values, and submit button label are tailored for <tt>@person</tt>.
# That works that way because the involved helpers know whether the resource is a new record or not,
# and generate HTML accordingly.
#
# The controller would receive the form data again in <tt>params[:person]</tt>, ready to be
# passed to <tt>Person#update</tt>:
#
# if @person.update(params[:person])
# # success
# else
# # error handling
# end
#
# That's how you typically work with resources.
module FormHelper
extend ActiveSupport::Concern
include FormTagHelper
include UrlHelper
include ModelNaming
include RecordIdentifier
attr_internal :default_form_builder
# Creates a form that allows the user to create or update the attributes
# of a specific model object.
#
# The method can be used in several slightly different ways, depending on
# how much you wish to rely on Rails to infer automatically from the model
# how the form should be constructed. For a generic model object, a form
# can be created by passing +form_for+ a string or symbol representing
# the object we are concerned with:
#
# <%= form_for :person do |f| %>
# First name: <%= f.text_field :first_name %><br />
# Last name : <%= f.text_field :last_name %><br />
# Biography : <%= f.text_area :biography %><br />
# Admin? : <%= f.check_box :admin %><br />
# <%= f.submit %>
# <% end %>
#
# The variable +f+ yielded to the block is a FormBuilder object that
# incorporates the knowledge about the model object represented by
# <tt>:person</tt> passed to +form_for+. Methods defined on the FormBuilder
# are used to generate fields bound to this model. Thus, for example,
#
# <%= f.text_field :first_name %>
#
# will get expanded to
#
# <%= text_field :person, :first_name %>
#
# which results in an HTML <tt><input></tt> tag whose +name+ attribute is
# <tt>person[first_name]</tt>. This means that when the form is submitted,
# the value entered by the user will be available in the controller as
# <tt>params[:person][:first_name]</tt>.
#
# For fields generated in this way using the FormBuilder,
# if <tt>:person</tt> also happens to be the name of an instance variable
# <tt>@person</tt>, the default value of the field shown when the form is
# initially displayed (e.g. in the situation where you are editing an
# existing record) will be the value of the corresponding attribute of
# <tt>@person</tt>.
#
# The rightmost argument to +form_for+ is an
# optional hash of options -
#
# * <tt>:url</tt> - The URL the form is to be submitted to. This may be
# represented in the same way as values passed to +url_for+ or +link_to+.
# So for example you may use a named route directly. When the model is
# represented by a string or symbol, as in the example above, if the
# <tt>:url</tt> option is not specified, by default the form will be
# sent back to the current URL (We will describe below an alternative
# resource-oriented usage of +form_for+ in which the URL does not need
# to be specified explicitly).
# * <tt>:namespace</tt> - A namespace for your form to ensure uniqueness of
# id attributes on form elements. The namespace attribute will be prefixed
# with underscore on the generated HTML id.
# * <tt>:method</tt> - The method to use when submitting the form, usually
# either "get" or "post". If "patch", "put", "delete", or another verb
# is used, a hidden input with name <tt>_method</tt> is added to
# simulate the verb over post.
# * <tt>:authenticity_token</tt> - Authenticity token to use in the form.
# Use only if you need to pass custom authenticity token string, or to
# not add authenticity_token field at all (by passing <tt>false</tt>).
# Remote forms may omit the embedded authenticity token by setting
# <tt>config.action_view.embed_authenticity_token_in_remote_forms = false</tt>.
# This is helpful when you're fragment-caching the form. Remote forms
# get the authenticity token from the <tt>meta</tt> tag, so embedding is
# unnecessary unless you support browsers without JavaScript.
# * <tt>:remote</tt> - If set to true, will allow the Unobtrusive
# JavaScript drivers to control the submit behavior. By default this
# behavior is an ajax submit.
# * <tt>:enforce_utf8</tt> - If set to false, a hidden input with name
# utf8 is not output.
# * <tt>:html</tt> - Optional HTML attributes for the form tag.
#
# Also note that +form_for+ doesn't create an exclusive scope. It's still
# possible to use both the stand-alone FormHelper methods and methods
# from FormTagHelper. For example:
#
# <%= form_for :person do |f| %>
# First name: <%= f.text_field :first_name %>
# Last name : <%= f.text_field :last_name %>
# Biography : <%= text_area :person, :biography %>
# Admin? : <%= check_box_tag "person[admin]", "1", @person.company.admin? %>
# <%= f.submit %>
# <% end %>
#
# This also works for the methods in FormOptionsHelper and DateHelper that
# are designed to work with an object as base, like
# FormOptionsHelper#collection_select and DateHelper#datetime_select.
#
# === #form_for with a model object
#
# In the examples above, the object to be created or edited was
# represented by a symbol passed to +form_for+, and we noted that
# a string can also be used equivalently. It is also possible, however,
# to pass a model object itself to +form_for+. For example, if <tt>@post</tt>
# is an existing record you wish to edit, you can create the form using
#
# <%= form_for @post do |f| %>
# ...
# <% end %>
#
# This behaves in almost the same way as outlined previously, with a
# couple of small exceptions. First, the prefix used to name the input
# elements within the form (hence the key that denotes them in the +params+
# hash) is actually derived from the object's _class_, e.g. <tt>params[:post]</tt>
# if the object's class is +Post+. However, this can be overwritten using
# the <tt>:as</tt> option, e.g. -
#
# <%= form_for(@person, as: :client) do |f| %>
# ...
# <% end %>
#
# would result in <tt>params[:client]</tt>.
#
# Secondly, the field values shown when the form is initially displayed
# are taken from the attributes of the object passed to +form_for+,
# regardless of whether the object is an instance
# variable. So, for example, if we had a _local_ variable +post+
# representing an existing record,
#
# <%= form_for post do |f| %>
# ...
# <% end %>
#
# would produce a form with fields whose initial state reflect the current
# values of the attributes of +post+.
#
# === Resource-oriented style
#
# In the examples just shown, although not indicated explicitly, we still
# need to use the <tt>:url</tt> option in order to specify where the
# form is going to be sent. However, further simplification is possible
# if the record passed to +form_for+ is a _resource_, i.e. it corresponds
# to a set of RESTful routes, e.g. defined using the +resources+ method
# in <tt>config/routes.rb</tt>. In this case Rails will simply infer the
# appropriate URL from the record itself. For example,
#
# <%= form_for @post do |f| %>
# ...
# <% end %>
#
# is then equivalent to something like:
#
# <%= form_for @post, as: :post, url: post_path(@post), method: :patch, html: { class: "edit_post", id: "edit_post_45" } do |f| %>
# ...
# <% end %>
#
# And for a new record
#
# <%= form_for(Post.new) do |f| %>
# ...
# <% end %>
#
# is equivalent to something like:
#
# <%= form_for @post, as: :post, url: posts_path, html: { class: "new_post", id: "new_post" } do |f| %>
# ...
# <% end %>
#
# However you can still overwrite individual conventions, such as:
#
# <%= form_for(@post, url: super_posts_path) do |f| %>
# ...
# <% end %>
#
# You can also set the answer format, like this:
#
# <%= form_for(@post, format: :json) do |f| %>
# ...
# <% end %>
#
# For namespaced routes, like +admin_post_url+:
#
# <%= form_for([:admin, @post]) do |f| %>
# ...
# <% end %>
#
# If your resource has associations defined, for example, you want to add comments
# to the document given that the routes are set correctly:
#
# <%= form_for([@document, @comment]) do |f| %>
# ...
# <% end %>
#
# Where <tt>@document = Document.find(params[:id])</tt> and
# <tt>@comment = Comment.new</tt>.
#
# === Setting the method
#
# You can force the form to use the full array of HTTP verbs by setting
#
# method: (:get|:post|:patch|:put|:delete)
#
# in the options hash. If the verb is not GET or POST, which are natively
# supported by HTML forms, the form will be set to POST and a hidden input
# called _method will carry the intended verb for the server to interpret.
#
# === Unobtrusive JavaScript
#
# Specifying:
#
# remote: true
#
# in the options hash creates a form that will allow the unobtrusive JavaScript drivers to modify its
# behavior. The expected default behavior is an XMLHttpRequest in the background instead of the regular
# POST arrangement, but ultimately the behavior is the choice of the JavaScript driver implementor.
# Even though it's using JavaScript to serialize the form elements, the form submission will work just like
# a regular submission as viewed by the receiving side (all elements available in <tt>params</tt>).
#
# Example:
#
# <%= form_for(@post, remote: true) do |f| %>
# ...
# <% end %>
#
# The HTML generated for this would be:
#
# <form action='http://www.example.com' method='post' data-remote='true'>
# <input name='_method' type='hidden' value='patch' />
# ...
# </form>
#
# === Setting HTML options
#
# You can set data attributes directly by passing in a data hash, but all other HTML options must be wrapped in
# the HTML key. Example:
#
# <%= form_for(@post, data: { behavior: "autosave" }, html: { name: "go" }) do |f| %>
# ...
# <% end %>
#
# The HTML generated for this would be:
#
# <form action='http://www.example.com' method='post' data-behavior='autosave' name='go'>
# <input name='_method' type='hidden' value='patch' />
# ...
# </form>
#
# === Removing hidden model id's
#
# The form_for method automatically includes the model id as a hidden field in the form.
# This is used to maintain the correlation between the form data and its associated model.
# Some ORM systems do not use IDs on nested models so in this case you want to be able
# to disable the hidden id.
#
# In the following example the Post model has many Comments stored within it in a NoSQL database,
# thus there is no primary key for comments.
#
# Example:
#
# <%= form_for(@post) do |f| %>
# <%= f.fields_for(:comments, include_id: false) do |cf| %>
# ...
# <% end %>
# <% end %>
#
# === Customized form builders
#
# You can also build forms using a customized FormBuilder class. Subclass
# FormBuilder and override or define some more helpers, then use your
# custom builder. For example, let's say you made a helper to
# automatically add labels to form inputs.
#
# <%= form_for @person, url: { action: "create" }, builder: LabellingFormBuilder do |f| %>
# <%= f.text_field :first_name %>
# <%= f.text_field :last_name %>
# <%= f.text_area :biography %>
# <%= f.check_box :admin %>
# <%= f.submit %>
# <% end %>
#
# In this case, if you use this:
#
# <%= render f %>
#
# The rendered template is <tt>people/_labelling_form</tt> and the local
# variable referencing the form builder is called
# <tt>labelling_form</tt>.
#
# The custom FormBuilder class is automatically merged with the options
# of a nested fields_for call, unless it's explicitly set.
#
# In many cases you will want to wrap the above in another helper, so you
# could do something like the following:
#
# def labelled_form_for(record_or_name_or_array, *args, &block)
# options = args.extract_options!
# form_for(record_or_name_or_array, *(args << options.merge(builder: LabellingFormBuilder)), &block)
# end
#
# If you don't need to attach a form to a model instance, then check out
# FormTagHelper#form_tag.
#
# === Form to external resources
#
# When you build forms to external resources sometimes you need to set an authenticity token or just render a form
# without it, for example when you submit data to a payment gateway number and types of fields could be limited.
#
# To set an authenticity token you need to pass an <tt>:authenticity_token</tt> parameter
#
# <%= form_for @invoice, url: external_url, authenticity_token: 'external_token' do |f| %>
# ...
# <% end %>
#
# If you don't want to an authenticity token field be rendered at all just pass <tt>false</tt>:
#
# <%= form_for @invoice, url: external_url, authenticity_token: false do |f| %>
# ...
# <% end %>
def form_for(record, options = {}, &block)
raise ArgumentError, "Missing block" unless block_given?
html_options = options[:html] ||= {}
case record
when String, Symbol
object_name = record
object = nil
else
object = record.is_a?(Array) ? record.last : record
raise ArgumentError, "First argument in form cannot contain nil or be empty" unless object
object_name = options[:as] || model_name_from_record_or_class(object).param_key
apply_form_for_options!(record, object, options)
end
html_options[:data] = options.delete(:data) if options.has_key?(:data)
html_options[:remote] = options.delete(:remote) if options.has_key?(:remote)
html_options[:method] = options.delete(:method) if options.has_key?(:method)
html_options[:enforce_utf8] = options.delete(:enforce_utf8) if options.has_key?(:enforce_utf8)
html_options[:authenticity_token] = options.delete(:authenticity_token)
builder = instantiate_builder(object_name, object, options)
output = capture(builder, &block)
html_options[:multipart] ||= builder.multipart?
html_options = html_options_for_form(options[:url] || {}, html_options)
form_tag_with_body(html_options, output)
end
def apply_form_for_options!(record, object, options) #:nodoc:
object = convert_to_model(object)
as = options[:as]
namespace = options[:namespace]
action, method = object.respond_to?(:persisted?) && object.persisted? ? [:edit, :patch] : [:new, :post]
options[:html].reverse_merge!(
class: as ? "#{action}_#{as}" : dom_class(object, action),
id: (as ? [namespace, action, as] : [namespace, dom_id(object, action)]).compact.join("_").presence,
method: method
)
options[:url] ||= if options.key?(:format)
polymorphic_path(record, format: options.delete(:format))
else
polymorphic_path(record, {})
end
end
private :apply_form_for_options!
mattr_accessor :form_with_generates_remote_forms, default: true
mattr_accessor :form_with_generates_ids, default: false
# Creates a form tag based on mixing URLs, scopes, or models.
#
# # Using just a URL:
# <%= form_with url: posts_path do |form| %>
# <%= form.text_field :title %>
# <% end %>
# # =>
# <form action="/posts" method="post" data-remote="true">
# <input type="text" name="title">
# </form>
#
# # Adding a scope prefixes the input field names:
# <%= form_with scope: :post, url: posts_path do |form| %>
# <%= form.text_field :title %>
# <% end %>
# # =>
# <form action="/posts" method="post" data-remote="true">
# <input type="text" name="post[title]">
# </form>
#
# # Using a model infers both the URL and scope:
# <%= form_with model: Post.new do |form| %>
# <%= form.text_field :title %>
# <% end %>
# # =>
# <form action="/posts" method="post" data-remote="true">
# <input type="text" name="post[title]">
# </form>
#
# # An existing model makes an update form and fills out field values:
# <%= form_with model: Post.first do |form| %>
# <%= form.text_field :title %>
# <% end %>
# # =>
# <form action="/posts/1" method="post" data-remote="true">
# <input type="hidden" name="_method" value="patch">
# <input type="text" name="post[title]" value="<the title of the post>">
# </form>
#
# # Though the fields don't have to correspond to model attributes:
# <%= form_with model: Cat.new do |form| %>
# <%= form.text_field :cats_dont_have_gills %>
# <%= form.text_field :but_in_forms_they_can %>
# <% end %>
# # =>
# <form action="/cats" method="post" data-remote="true">
# <input type="text" name="cat[cats_dont_have_gills]">
# <input type="text" name="cat[but_in_forms_they_can]">
# </form>
#
# The parameters in the forms are accessible in controllers according to
# their name nesting. So inputs named +title+ and <tt>post[title]</tt> are
# accessible as <tt>params[:title]</tt> and <tt>params[:post][:title]</tt>
# respectively.
#
# By default +form_with+ attaches the <tt>data-remote</tt> attribute
# submitting the form via an XMLHTTPRequest in the background if an
# Unobtrusive JavaScript driver, like rails-ujs, is used. See the
# <tt>:local</tt> option for more.
#
# For ease of comparison the examples above left out the submit button,
# as well as the auto generated hidden fields that enable UTF-8 support
# and adds an authenticity token needed for cross site request forgery
# protection.
#
# === Resource-oriented style
#
# In many of the examples just shown, the +:model+ passed to +form_with+
# is a _resource_. It corresponds to a set of RESTful routes, most likely
# defined via +resources+ in <tt>config/routes.rb</tt>.
#
# So when passing such a model record, Rails infers the URL and method.
#
# <%= form_with model: @post do |form| %>
# ...
# <% end %>
#
# is then equivalent to something like:
#
# <%= form_with scope: :post, url: post_path(@post), method: :patch do |form| %>
# ...
# <% end %>
#
# And for a new record
#
# <%= form_with model: Post.new do |form| %>
# ...
# <% end %>
#
# is equivalent to something like:
#
# <%= form_with scope: :post, url: posts_path do |form| %>
# ...
# <% end %>
#
# ==== +form_with+ options
#
# * <tt>:url</tt> - The URL the form submits to. Akin to values passed to
# +url_for+ or +link_to+. For example, you may use a named route
# directly. When a <tt>:scope</tt> is passed without a <tt>:url</tt> the
# form just submits to the current URL.
# * <tt>:method</tt> - The method to use when submitting the form, usually
# either "get" or "post". If "patch", "put", "delete", or another verb
# is used, a hidden input named <tt>_method</tt> is added to
# simulate the verb over post.
# * <tt>:format</tt> - The format of the route the form submits to.
# Useful when submitting to another resource type, like <tt>:json</tt>.
# Skipped if a <tt>:url</tt> is passed.
# * <tt>:scope</tt> - The scope to prefix input field names with and
# thereby how the submitted parameters are grouped in controllers.
# * <tt>:model</tt> - A model object to infer the <tt>:url</tt> and
# <tt>:scope</tt> by, plus fill out input field values.
# So if a +title+ attribute is set to "Ahoy!" then a +title+ input
# field's value would be "Ahoy!".
# If the model is a new record a create form is generated, if an
# existing record, however, an update form is generated.
# Pass <tt>:scope</tt> or <tt>:url</tt> to override the defaults.
# E.g. turn <tt>params[:post]</tt> into <tt>params[:article]</tt>.
# * <tt>:authenticity_token</tt> - Authenticity token to use in the form.
# Override with a custom authenticity token or pass <tt>false</tt> to
# skip the authenticity token field altogether.
# Useful when submitting to an external resource like a payment gateway
# that might limit the valid fields.
# Remote forms may omit the embedded authenticity token by setting
# <tt>config.action_view.embed_authenticity_token_in_remote_forms = false</tt>.
# This is helpful when fragment-caching the form. Remote forms
# get the authenticity token from the <tt>meta</tt> tag, so embedding is
# unnecessary unless you support browsers without JavaScript.
# * <tt>:local</tt> - By default form submits are remote and unobtrusive XHRs.
# Disable remote submits with <tt>local: true</tt>.
# * <tt>:skip_enforcing_utf8</tt> - By default a hidden field named +utf8+
# is output to enforce UTF-8 submits. Set to true to skip the field.
# * <tt>:builder</tt> - Override the object used to build the form.
# * <tt>:id</tt> - Optional HTML id attribute.
# * <tt>:class</tt> - Optional HTML class attribute.
# * <tt>:data</tt> - Optional HTML data attributes.
# * <tt>:html</tt> - Other optional HTML attributes for the form tag.
#
# === Examples
#
# When not passing a block, +form_with+ just generates an opening form tag.
#
# <%= form_with(model: @post, url: super_posts_path) %>
# <%= form_with(model: @post, scope: :article) %>
# <%= form_with(model: @post, format: :json) %>
# <%= form_with(model: @post, authenticity_token: false) %> # Disables the token.
#
# For namespaced routes, like +admin_post_url+:
#
# <%= form_with(model: [ :admin, @post ]) do |form| %>
# ...
# <% end %>
#
# If your resource has associations defined, for example, you want to add comments
# to the document given that the routes are set correctly:
#
# <%= form_with(model: [ @document, Comment.new ]) do |form| %>
# ...
# <% end %>
#
# Where <tt>@document = Document.find(params[:id])</tt>.
#
# === Mixing with other form helpers
#
# While +form_with+ uses a FormBuilder object it's possible to mix and
# match the stand-alone FormHelper methods and methods
# from FormTagHelper:
#
# <%= form_with scope: :person do |form| %>
# <%= form.text_field :first_name %>
# <%= form.text_field :last_name %>
#
# <%= text_area :person, :biography %>
# <%= check_box_tag "person[admin]", "1", @person.company.admin? %>
#
# <%= form.submit %>
# <% end %>
#
# Same goes for the methods in FormOptionsHelper and DateHelper designed
# to work with an object as a base, like
# FormOptionsHelper#collection_select and DateHelper#datetime_select.
#
# === Setting the method
#
# You can force the form to use the full array of HTTP verbs by setting
#
# method: (:get|:post|:patch|:put|:delete)
#
# in the options hash. If the verb is not GET or POST, which are natively
# supported by HTML forms, the form will be set to POST and a hidden input
# called _method will carry the intended verb for the server to interpret.
#
# === Setting HTML options
#
# You can set data attributes directly in a data hash, but HTML options
# besides id and class must be wrapped in an HTML key:
#
# <%= form_with(model: @post, data: { behavior: "autosave" }, html: { name: "go" }) do |form| %>
# ...
# <% end %>
#
# generates
#
# <form action="/posts/123" method="post" data-behavior="autosave" name="go">
# <input name="_method" type="hidden" value="patch" />
# ...
# </form>
#
# === Removing hidden model id's
#
# The +form_with+ method automatically includes the model id as a hidden field in the form.
# This is used to maintain the correlation between the form data and its associated model.
# Some ORM systems do not use IDs on nested models so in this case you want to be able
# to disable the hidden id.
#
# In the following example the Post model has many Comments stored within it in a NoSQL database,
# thus there is no primary key for comments.
#
# <%= form_with(model: @post) do |form| %>
# <%= form.fields(:comments, skip_id: true) do |fields| %>
# ...
# <% end %>
# <% end %>
#
# === Customized form builders
#
# You can also build forms using a customized FormBuilder class. Subclass
# FormBuilder and override or define some more helpers, then use your
# custom builder. For example, let's say you made a helper to
# automatically add labels to form inputs.
#
# <%= form_with model: @person, url: { action: "create" }, builder: LabellingFormBuilder do |form| %>
# <%= form.text_field :first_name %>
# <%= form.text_field :last_name %>
# <%= form.text_area :biography %>
# <%= form.check_box :admin %>
# <%= form.submit %>
# <% end %>
#
# In this case, if you use:
#
# <%= render form %>
#
# The rendered template is <tt>people/_labelling_form</tt> and the local
# variable referencing the form builder is called
# <tt>labelling_form</tt>.
#
# The custom FormBuilder class is automatically merged with the options
# of a nested +fields+ call, unless it's explicitly set.
#
# In many cases you will want to wrap the above in another helper, so you
# could do something like the following:
#
# def labelled_form_with(**options, &block)
# form_with(**options.merge(builder: LabellingFormBuilder), &block)
# end
def form_with(model: nil, scope: nil, url: nil, format: nil, **options)
options[:allow_method_names_outside_object] = true
options[:skip_default_ids] = !form_with_generates_ids
if model
url ||= polymorphic_path(model, format: format)
model = model.last if model.is_a?(Array)
scope ||= model_name_from_record_or_class(model).param_key
end
if block_given?
builder = instantiate_builder(scope, model, options)
output = capture(builder, &Proc.new)
options[:multipart] ||= builder.multipart?
html_options = html_options_for_form_with(url, model, options)
form_tag_with_body(html_options, output)
else
html_options = html_options_for_form_with(url, model, options)
form_tag_html(html_options)
end
end
# Creates a scope around a specific model object like form_for, but
# doesn't create the form tags themselves. This makes fields_for suitable
# for specifying additional model objects in the same form.
#
# Although the usage and purpose of +fields_for+ is similar to +form_for+'s,
# its method signature is slightly different. Like +form_for+, it yields
# a FormBuilder object associated with a particular model object to a block,
# and within the block allows methods to be called on the builder to
# generate fields associated with the model object. Fields may reflect
# a model object in two ways - how they are named (hence how submitted
# values appear within the +params+ hash in the controller) and what
# default values are shown when the form the fields appear in is first
# displayed. In order for both of these features to be specified independently,
# both an object name (represented by either a symbol or string) and the
# object itself can be passed to the method separately -
#
# <%= form_for @person do |person_form| %>
# First name: <%= person_form.text_field :first_name %>
# Last name : <%= person_form.text_field :last_name %>
#
# <%= fields_for :permission, @person.permission do |permission_fields| %>
# Admin? : <%= permission_fields.check_box :admin %>
# <% end %>
#
# <%= person_form.submit %>
# <% end %>
#
# In this case, the checkbox field will be represented by an HTML +input+
# tag with the +name+ attribute <tt>permission[admin]</tt>, and the submitted
# value will appear in the controller as <tt>params[:permission][:admin]</tt>.
# If <tt>@person.permission</tt> is an existing record with an attribute
# +admin+, the initial state of the checkbox when first displayed will
# reflect the value of <tt>@person.permission.admin</tt>.
#
# Often this can be simplified by passing just the name of the model
# object to +fields_for+ -
#
# <%= fields_for :permission do |permission_fields| %>
# Admin?: <%= permission_fields.check_box :admin %>
# <% end %>
#
# ...in which case, if <tt>:permission</tt> also happens to be the name of an
# instance variable <tt>@permission</tt>, the initial state of the input
# field will reflect the value of that variable's attribute <tt>@permission.admin</tt>.
#
# Alternatively, you can pass just the model object itself (if the first
# argument isn't a string or symbol +fields_for+ will realize that the
# name has been omitted) -
#
# <%= fields_for @person.permission do |permission_fields| %>
# Admin?: <%= permission_fields.check_box :admin %>
# <% end %>
#
# and +fields_for+ will derive the required name of the field from the
# _class_ of the model object, e.g. if <tt>@person.permission</tt>, is
# of class +Permission+, the field will still be named <tt>permission[admin]</tt>.
#
# Note: This also works for the methods in FormOptionsHelper and
# DateHelper that are designed to work with an object as base, like
# FormOptionsHelper#collection_select and DateHelper#datetime_select.
#
# === Nested Attributes Examples
#
# When the object belonging to the current scope has a nested attribute
# writer for a certain attribute, fields_for will yield a new scope
# for that attribute. This allows you to create forms that set or change
# the attributes of a parent object and its associations in one go.
#
# Nested attribute writers are normal setter methods named after an
# association. The most common way of defining these writers is either
# with +accepts_nested_attributes_for+ in a model definition or by
# defining a method with the proper name. For example: the attribute
# writer for the association <tt>:address</tt> is called
# <tt>address_attributes=</tt>.
#
# Whether a one-to-one or one-to-many style form builder will be yielded
# depends on whether the normal reader method returns a _single_ object
# or an _array_ of objects.
#
# ==== One-to-one
#
# Consider a Person class which returns a _single_ Address from the
# <tt>address</tt> reader method and responds to the
# <tt>address_attributes=</tt> writer method:
#
# class Person
# def address
# @address
# end
#
# def address_attributes=(attributes)
# # Process the attributes hash
# end
# end
#
# This model can now be used with a nested fields_for, like so:
#
# <%= form_for @person do |person_form| %>
# ...
# <%= person_form.fields_for :address do |address_fields| %>
# Street : <%= address_fields.text_field :street %>
# Zip code: <%= address_fields.text_field :zip_code %>
# <% end %>
# ...
# <% end %>
#
# When address is already an association on a Person you can use
# +accepts_nested_attributes_for+ to define the writer method for you:
#
# class Person < ActiveRecord::Base
# has_one :address
# accepts_nested_attributes_for :address
# end
#
# If you want to destroy the associated model through the form, you have
# to enable it first using the <tt>:allow_destroy</tt> option for
# +accepts_nested_attributes_for+:
#
# class Person < ActiveRecord::Base
# has_one :address
# accepts_nested_attributes_for :address, allow_destroy: true
# end
#
# Now, when you use a form element with the <tt>_destroy</tt> parameter,
# with a value that evaluates to +true+, you will destroy the associated
# model (eg. 1, '1', true, or 'true'):
#
# <%= form_for @person do |person_form| %>
# ...
# <%= person_form.fields_for :address do |address_fields| %>
# ...
# Delete: <%= address_fields.check_box :_destroy %>
# <% end %>
# ...
# <% end %>
#
# ==== One-to-many
#
# Consider a Person class which returns an _array_ of Project instances
# from the <tt>projects</tt> reader method and responds to the
# <tt>projects_attributes=</tt> writer method:
#
# class Person
# def projects
# [@project1, @project2]
# end
#
# def projects_attributes=(attributes)
# # Process the attributes hash
# end
# end
#
# Note that the <tt>projects_attributes=</tt> writer method is in fact
# required for fields_for to correctly identify <tt>:projects</tt> as a
# collection, and the correct indices to be set in the form markup.
#
# When projects is already an association on Person you can use
# +accepts_nested_attributes_for+ to define the writer method for you:
#
# class Person < ActiveRecord::Base
# has_many :projects
# accepts_nested_attributes_for :projects
# end
#
# This model can now be used with a nested fields_for. The block given to
# the nested fields_for call will be repeated for each instance in the
# collection:
#
# <%= form_for @person do |person_form| %>
# ...
# <%= person_form.fields_for :projects do |project_fields| %>
# <% if project_fields.object.active? %>
# Name: <%= project_fields.text_field :name %>
# <% end %>
# <% end %>
# ...
# <% end %>
#
# It's also possible to specify the instance to be used:
#
# <%= form_for @person do |person_form| %>
# ...
# <% @person.projects.each do |project| %>
# <% if project.active? %>
# <%= person_form.fields_for :projects, project do |project_fields| %>
# Name: <%= project_fields.text_field :name %>
# <% end %>
# <% end %>
# <% end %>
# ...
# <% end %>
#
# Or a collection to be used:
#
# <%= form_for @person do |person_form| %>
# ...
# <%= person_form.fields_for :projects, @active_projects do |project_fields| %>
# Name: <%= project_fields.text_field :name %>
# <% end %>
# ...
# <% end %>
#
# If you want to destroy any of the associated models through the
# form, you have to enable it first using the <tt>:allow_destroy</tt>
# option for +accepts_nested_attributes_for+:
#
# class Person < ActiveRecord::Base
# has_many :projects
# accepts_nested_attributes_for :projects, allow_destroy: true
# end
#
# This will allow you to specify which models to destroy in the
# attributes hash by adding a form element for the <tt>_destroy</tt>
# parameter with a value that evaluates to +true+
# (eg. 1, '1', true, or 'true'):
#
# <%= form_for @person do |person_form| %>
# ...
# <%= person_form.fields_for :projects do |project_fields| %>
# Delete: <%= project_fields.check_box :_destroy %>
# <% end %>
# ...
# <% end %>
#
# When a collection is used you might want to know the index of each
# object into the array. For this purpose, the <tt>index</tt> method
# is available in the FormBuilder object.
#
# <%= form_for @person do |person_form| %>
# ...
# <%= person_form.fields_for :projects do |project_fields| %>
# Project #<%= project_fields.index %>
# ...
# <% end %>
# ...
# <% end %>
#
# Note that fields_for will automatically generate a hidden field
# to store the ID of the record. There are circumstances where this
# hidden field is not needed and you can pass <tt>include_id: false</tt>
# to prevent fields_for from rendering it automatically.
def fields_for(record_name, record_object = nil, options = {}, &block)
builder = instantiate_builder(record_name, record_object, options)
capture(builder, &block)
end
# Scopes input fields with either an explicit scope or model.
# Like +form_with+ does with <tt>:scope</tt> or <tt>:model</tt>,
# except it doesn't output the form tags.
#
# # Using a scope prefixes the input field names:
# <%= fields :comment do |fields| %>
# <%= fields.text_field :body %>
# <% end %>
# # => <input type="text" name="comment[body]">
#
# # Using a model infers the scope and assigns field values:
# <%= fields model: Comment.new(body: "full bodied") do |fields| %>
# <%= fields.text_field :body %>
# <% end %>
# # => <input type="text" name="comment[body]" value="full bodied">
#
# # Using +fields+ with +form_with+:
# <%= form_with model: @post do |form| %>
# <%= form.text_field :title %>
#
# <%= form.fields :comment do |fields| %>
# <%= fields.text_field :body %>
# <% end %>
# <% end %>
#
# Much like +form_with+ a FormBuilder instance associated with the scope
# or model is yielded, so any generated field names are prefixed with
# either the passed scope or the scope inferred from the <tt>:model</tt>.
#
# === Mixing with other form helpers
#
# While +form_with+ uses a FormBuilder object it's possible to mix and
# match the stand-alone FormHelper methods and methods
# from FormTagHelper:
#
# <%= fields model: @comment do |fields| %>
# <%= fields.text_field :body %>
#
# <%= text_area :commenter, :biography %>
# <%= check_box_tag "comment[all_caps]", "1", @comment.commenter.hulk_mode? %>
# <% end %>
#
# Same goes for the methods in FormOptionsHelper and DateHelper designed
# to work with an object as a base, like
# FormOptionsHelper#collection_select and DateHelper#datetime_select.
def fields(scope = nil, model: nil, **options, &block)
options[:allow_method_names_outside_object] = true
options[:skip_default_ids] = !form_with_generates_ids
if model
scope ||= model_name_from_record_or_class(model).param_key
end
builder = instantiate_builder(scope, model, options)
capture(builder, &block)
end
# Returns a label tag tailored for labelling an input field for a specified attribute (identified by +method+) on an object
# assigned to the template (identified by +object+). The text of label will default to the attribute name unless a translation
# is found in the current I18n locale (through helpers.label.<modelname>.<attribute>) or you specify it explicitly.
# Additional options on the label tag can be passed as a hash with +options+. These options will be tagged
# onto the HTML as an HTML element attribute as in the example shown, except for the <tt>:value</tt> option, which is designed to
# target labels for radio_button tags (where the value is used in the ID of the input tag).
#
# ==== Examples
# label(:post, :title)
# # => <label for="post_title">Title</label>
#
# You can localize your labels based on model and attribute names.
# For example you can define the following in your locale (e.g. en.yml)
#
# helpers:
# label:
# post:
# body: "Write your entire text here"
#
# Which then will result in
#
# label(:post, :body)
# # => <label for="post_body">Write your entire text here</label>
#
# Localization can also be based purely on the translation of the attribute-name
# (if you are using ActiveRecord):
#
# activerecord:
# attributes:
# post:
# cost: "Total cost"
#
# label(:post, :cost)
# # => <label for="post_cost">Total cost</label>
#
# label(:post, :title, "A short title")
# # => <label for="post_title">A short title</label>
#
# label(:post, :title, "A short title", class: "title_label")
# # => <label for="post_title" class="title_label">A short title</label>
#
# label(:post, :privacy, "Public Post", value: "public")
# # => <label for="post_privacy_public">Public Post</label>
#
# label(:post, :terms) do
# raw('Accept <a href="/terms">Terms</a>.')
# end
# # => <label for="post_terms">Accept <a href="/terms">Terms</a>.</label>
def label(object_name, method, content_or_options = nil, options = nil, &block)
Tags::Label.new(object_name, method, self, content_or_options, options).render(&block)
end
# Returns an input tag of the "text" type tailored for accessing a specified attribute (identified by +method+) on an object
# assigned to the template (identified by +object+). Additional options on the input tag can be passed as a
# hash with +options+. These options will be tagged onto the HTML as an HTML element attribute as in the example
# shown.
#
# ==== Examples
# text_field(:post, :title, size: 20)
# # => <input type="text" id="post_title" name="post[title]" size="20" value="#{@post.title}" />
#
# text_field(:post, :title, class: "create_input")
# # => <input type="text" id="post_title" name="post[title]" value="#{@post.title}" class="create_input" />
#
# text_field(:session, :user, onchange: "if ($('#session_user').val() === 'admin') { alert('Your login cannot be admin!'); }")
# # => <input type="text" id="session_user" name="session[user]" value="#{@session.user}" onchange="if ($('#session_user').val() === 'admin') { alert('Your login cannot be admin!'); }"/>
#
# text_field(:snippet, :code, size: 20, class: 'code_input')
# # => <input type="text" id="snippet_code" name="snippet[code]" size="20" value="#{@snippet.code}" class="code_input" />
def text_field(object_name, method, options = {})
Tags::TextField.new(object_name, method, self, options).render
end
# Returns an input tag of the "password" type tailored for accessing a specified attribute (identified by +method+) on an object
# assigned to the template (identified by +object+). Additional options on the input tag can be passed as a
# hash with +options+. These options will be tagged onto the HTML as an HTML element attribute as in the example
# shown. For security reasons this field is blank by default; pass in a value via +options+ if this is not desired.
#
# ==== Examples
# password_field(:login, :pass, size: 20)
# # => <input type="password" id="login_pass" name="login[pass]" size="20" />
#
# password_field(:account, :secret, class: "form_input", value: @account.secret)
# # => <input type="password" id="account_secret" name="account[secret]" value="#{@account.secret}" class="form_input" />
#
# password_field(:user, :password, onchange: "if ($('#user_password').val().length > 30) { alert('Your password needs to be shorter!'); }")
# # => <input type="password" id="user_password" name="user[password]" onchange="if ($('#user_password').val().length > 30) { alert('Your password needs to be shorter!'); }"/>
#
# password_field(:account, :pin, size: 20, class: 'form_input')
# # => <input type="password" id="account_pin" name="account[pin]" size="20" class="form_input" />
def password_field(object_name, method, options = {})
Tags::PasswordField.new(object_name, method, self, options).render
end
# Returns a hidden input tag tailored for accessing a specified attribute (identified by +method+) on an object
# assigned to the template (identified by +object+). Additional options on the input tag can be passed as a
# hash with +options+. These options will be tagged onto the HTML as an HTML element attribute as in the example
# shown.
#
# ==== Examples
# hidden_field(:signup, :pass_confirm)
# # => <input type="hidden" id="signup_pass_confirm" name="signup[pass_confirm]" value="#{@signup.pass_confirm}" />
#
# hidden_field(:post, :tag_list)
# # => <input type="hidden" id="post_tag_list" name="post[tag_list]" value="#{@post.tag_list}" />
#
# hidden_field(:user, :token)
# # => <input type="hidden" id="user_token" name="user[token]" value="#{@user.token}" />
def hidden_field(object_name, method, options = {})
Tags::HiddenField.new(object_name, method, self, options).render
end
# Returns a file upload input tag tailored for accessing a specified attribute (identified by +method+) on an object
# assigned to the template (identified by +object+). Additional options on the input tag can be passed as a
# hash with +options+. These options will be tagged onto the HTML as an HTML element attribute as in the example
# shown.
#
# Using this method inside a +form_for+ block will set the enclosing form's encoding to <tt>multipart/form-data</tt>.
#
# ==== Options
# * Creates standard HTML attributes for the tag.
# * <tt>:disabled</tt> - If set to true, the user will not be able to use this input.
# * <tt>:multiple</tt> - If set to true, *in most updated browsers* the user will be allowed to select multiple files.
# * <tt>:accept</tt> - If set to one or multiple mime-types, the user will be suggested a filter when choosing a file. You still need to set up model validations.
#
# ==== Examples
# file_field(:user, :avatar)
# # => <input type="file" id="user_avatar" name="user[avatar]" />
#
# file_field(:post, :image, multiple: true)
# # => <input type="file" id="post_image" name="post[image][]" multiple="multiple" />
#
# file_field(:post, :attached, accept: 'text/html')
# # => <input accept="text/html" type="file" id="post_attached" name="post[attached]" />
#
# file_field(:post, :image, accept: 'image/png,image/gif,image/jpeg')
# # => <input type="file" id="post_image" name="post[image]" accept="image/png,image/gif,image/jpeg" />
#
# file_field(:attachment, :file, class: 'file_input')
# # => <input type="file" id="attachment_file" name="attachment[file]" class="file_input" />
def file_field(object_name, method, options = {})
Tags::FileField.new(object_name, method, self, convert_direct_upload_option_to_url(options.dup)).render
end
# Returns a textarea opening and closing tag set tailored for accessing a specified attribute (identified by +method+)
# on an object assigned to the template (identified by +object+). Additional options on the input tag can be passed as a
# hash with +options+.
#
# ==== Examples
# text_area(:post, :body, cols: 20, rows: 40)
# # => <textarea cols="20" rows="40" id="post_body" name="post[body]">
# # #{@post.body}
# # </textarea>
#
# text_area(:comment, :text, size: "20x30")
# # => <textarea cols="20" rows="30" id="comment_text" name="comment[text]">
# # #{@comment.text}
# # </textarea>
#
# text_area(:application, :notes, cols: 40, rows: 15, class: 'app_input')
# # => <textarea cols="40" rows="15" id="application_notes" name="application[notes]" class="app_input">
# # #{@application.notes}
# # </textarea>
#
# text_area(:entry, :body, size: "20x20", disabled: 'disabled')
# # => <textarea cols="20" rows="20" id="entry_body" name="entry[body]" disabled="disabled">
# # #{@entry.body}
# # </textarea>
def text_area(object_name, method, options = {})
Tags::TextArea.new(object_name, method, self, options).render
end
# Returns a checkbox tag tailored for accessing a specified attribute (identified by +method+) on an object
# assigned to the template (identified by +object+). This object must be an instance object (@object) and not a local object.
# It's intended that +method+ returns an integer and if that integer is above zero, then the checkbox is checked.
# Additional options on the input tag can be passed as a hash with +options+. The +checked_value+ defaults to 1
# while the default +unchecked_value+ is set to 0 which is convenient for boolean values.
#
# ==== Gotcha
#
# The HTML specification says unchecked check boxes are not successful, and
# thus web browsers do not send them. Unfortunately this introduces a gotcha:
# if an +Invoice+ model has a +paid+ flag, and in the form that edits a paid
# invoice the user unchecks its check box, no +paid+ parameter is sent. So,
# any mass-assignment idiom like
#
# @invoice.update(params[:invoice])
#
# wouldn't update the flag.
#
# To prevent this the helper generates an auxiliary hidden field before
# the very check box. The hidden field has the same name and its
# attributes mimic an unchecked check box.
#
# This way, the client either sends only the hidden field (representing
# the check box is unchecked), or both fields. Since the HTML specification
# says key/value pairs have to be sent in the same order they appear in the
# form, and parameters extraction gets the last occurrence of any repeated
# key in the query string, that works for ordinary forms.
#
# Unfortunately that workaround does not work when the check box goes
# within an array-like parameter, as in
#
# <%= fields_for "project[invoice_attributes][]", invoice, index: nil do |form| %>
# <%= form.check_box :paid %>
# ...
# <% end %>
#
# because parameter name repetition is precisely what Rails seeks to distinguish
# the elements of the array. For each item with a checked check box you
# get an extra ghost item with only that attribute, assigned to "0".
#
# In that case it is preferable to either use +check_box_tag+ or to use
# hashes instead of arrays.
#
# # Let's say that @post.validated? is 1:
# check_box("post", "validated")
# # => <input name="post[validated]" type="hidden" value="0" />
# # <input checked="checked" type="checkbox" id="post_validated" name="post[validated]" value="1" />
#
# # Let's say that @puppy.gooddog is "no":
# check_box("puppy", "gooddog", {}, "yes", "no")
# # => <input name="puppy[gooddog]" type="hidden" value="no" />
# # <input type="checkbox" id="puppy_gooddog" name="puppy[gooddog]" value="yes" />
#
# check_box("eula", "accepted", { class: 'eula_check' }, "yes", "no")
# # => <input name="eula[accepted]" type="hidden" value="no" />
# # <input type="checkbox" class="eula_check" id="eula_accepted" name="eula[accepted]" value="yes" />
def check_box(object_name, method, options = {}, checked_value = "1", unchecked_value = "0")
Tags::CheckBox.new(object_name, method, self, checked_value, unchecked_value, options).render
end
# Returns a radio button tag for accessing a specified attribute (identified by +method+) on an object
# assigned to the template (identified by +object+). If the current value of +method+ is +tag_value+ the
# radio button will be checked.
#
# To force the radio button to be checked pass <tt>checked: true</tt> in the
# +options+ hash. You may pass HTML options there as well.
#
# # Let's say that @post.category returns "rails":
# radio_button("post", "category", "rails")
# radio_button("post", "category", "java")
# # => <input type="radio" id="post_category_rails" name="post[category]" value="rails" checked="checked" />
# # <input type="radio" id="post_category_java" name="post[category]" value="java" />
#
# # Let's say that @user.receive_newsletter returns "no":
# radio_button("user", "receive_newsletter", "yes")
# radio_button("user", "receive_newsletter", "no")
# # => <input type="radio" id="user_receive_newsletter_yes" name="user[receive_newsletter]" value="yes" />
# # <input type="radio" id="user_receive_newsletter_no" name="user[receive_newsletter]" value="no" checked="checked" />
def radio_button(object_name, method, tag_value, options = {})
Tags::RadioButton.new(object_name, method, self, tag_value, options).render
end
# Returns a text_field of type "color".
#
# color_field("car", "color")
# # => <input id="car_color" name="car[color]" type="color" value="#000000" />
def color_field(object_name, method, options = {})
Tags::ColorField.new(object_name, method, self, options).render
end
# Returns an input of type "search" for accessing a specified attribute (identified by +method+) on an object
# assigned to the template (identified by +object_name+). Inputs of type "search" may be styled differently by
# some browsers.
#
# search_field(:user, :name)
# # => <input id="user_name" name="user[name]" type="search" />
# search_field(:user, :name, autosave: false)
# # => <input autosave="false" id="user_name" name="user[name]" type="search" />
# search_field(:user, :name, results: 3)
# # => <input id="user_name" name="user[name]" results="3" type="search" />
# # Assume request.host returns "www.example.com"
# search_field(:user, :name, autosave: true)
# # => <input autosave="com.example.www" id="user_name" name="user[name]" results="10" type="search" />
# search_field(:user, :name, onsearch: true)
# # => <input id="user_name" incremental="true" name="user[name]" onsearch="true" type="search" />
# search_field(:user, :name, autosave: false, onsearch: true)
# # => <input autosave="false" id="user_name" incremental="true" name="user[name]" onsearch="true" type="search" />
# search_field(:user, :name, autosave: true, onsearch: true)
# # => <input autosave="com.example.www" id="user_name" incremental="true" name="user[name]" onsearch="true" results="10" type="search" />
def search_field(object_name, method, options = {})
Tags::SearchField.new(object_name, method, self, options).render
end
# Returns a text_field of type "tel".
#
# telephone_field("user", "phone")
# # => <input id="user_phone" name="user[phone]" type="tel" />
#
def telephone_field(object_name, method, options = {})
Tags::TelField.new(object_name, method, self, options).render
end
# aliases telephone_field
alias phone_field telephone_field
# Returns a text_field of type "date".
#
# date_field("user", "born_on")
# # => <input id="user_born_on" name="user[born_on]" type="date" />
#
# The default value is generated by trying to call +strftime+ with "%Y-%m-%d"
# on the object's value, which makes it behave as expected for instances
# of DateTime and ActiveSupport::TimeWithZone. You can still override that
# by passing the "value" option explicitly, e.g.
#
# @user.born_on = Date.new(1984, 1, 27)
# date_field("user", "born_on", value: "1984-05-12")
# # => <input id="user_born_on" name="user[born_on]" type="date" value="1984-05-12" />
#
# You can create values for the "min" and "max" attributes by passing
# instances of Date or Time to the options hash.
#
# date_field("user", "born_on", min: Date.today)
# # => <input id="user_born_on" name="user[born_on]" type="date" min="2014-05-20" />
#
# Alternatively, you can pass a String formatted as an ISO8601 date as the
# values for "min" and "max."
#
# date_field("user", "born_on", min: "2014-05-20")
# # => <input id="user_born_on" name="user[born_on]" type="date" min="2014-05-20" />
#
def date_field(object_name, method, options = {})
Tags::DateField.new(object_name, method, self, options).render
end
# Returns a text_field of type "time".
#
# The default value is generated by trying to call +strftime+ with "%T.%L"
# on the object's value. It is still possible to override that
# by passing the "value" option.
#
# === Options
# * Accepts same options as time_field_tag
#
# === Example
# time_field("task", "started_at")
# # => <input id="task_started_at" name="task[started_at]" type="time" />
#
# You can create values for the "min" and "max" attributes by passing
# instances of Date or Time to the options hash.
#
# time_field("task", "started_at", min: Time.now)
# # => <input id="task_started_at" name="task[started_at]" type="time" min="01:00:00.000" />
#
# Alternatively, you can pass a String formatted as an ISO8601 time as the
# values for "min" and "max."
#
# time_field("task", "started_at", min: "01:00:00")
# # => <input id="task_started_at" name="task[started_at]" type="time" min="01:00:00.000" />
#
def time_field(object_name, method, options = {})
Tags::TimeField.new(object_name, method, self, options).render
end
# Returns a text_field of type "datetime-local".
#
# datetime_field("user", "born_on")
# # => <input id="user_born_on" name="user[born_on]" type="datetime-local" />
#
# The default value is generated by trying to call +strftime+ with "%Y-%m-%dT%T"
# on the object's value, which makes it behave as expected for instances
# of DateTime and ActiveSupport::TimeWithZone.
#
# @user.born_on = Date.new(1984, 1, 12)
# datetime_field("user", "born_on")
# # => <input id="user_born_on" name="user[born_on]" type="datetime-local" value="1984-01-12T00:00:00" />
#
# You can create values for the "min" and "max" attributes by passing
# instances of Date or Time to the options hash.
#
# datetime_field("user", "born_on", min: Date.today)
# # => <input id="user_born_on" name="user[born_on]" type="datetime-local" min="2014-05-20T00:00:00.000" />
#
# Alternatively, you can pass a String formatted as an ISO8601 datetime as
# the values for "min" and "max."
#
# datetime_field("user", "born_on", min: "2014-05-20T00:00:00")
# # => <input id="user_born_on" name="user[born_on]" type="datetime-local" min="2014-05-20T00:00:00.000" />
#
def datetime_field(object_name, method, options = {})
Tags::DatetimeLocalField.new(object_name, method, self, options).render
end
alias datetime_local_field datetime_field
# Returns a text_field of type "month".
#
# month_field("user", "born_on")
# # => <input id="user_born_on" name="user[born_on]" type="month" />
#
# The default value is generated by trying to call +strftime+ with "%Y-%m"
# on the object's value, which makes it behave as expected for instances
# of DateTime and ActiveSupport::TimeWithZone.
#
# @user.born_on = Date.new(1984, 1, 27)
# month_field("user", "born_on")
# # => <input id="user_born_on" name="user[born_on]" type="date" value="1984-01" />
#
def month_field(object_name, method, options = {})
Tags::MonthField.new(object_name, method, self, options).render
end
# Returns a text_field of type "week".
#
# week_field("user", "born_on")
# # => <input id="user_born_on" name="user[born_on]" type="week" />
#
# The default value is generated by trying to call +strftime+ with "%Y-W%W"
# on the object's value, which makes it behave as expected for instances
# of DateTime and ActiveSupport::TimeWithZone.
#
# @user.born_on = Date.new(1984, 5, 12)
# week_field("user", "born_on")
# # => <input id="user_born_on" name="user[born_on]" type="date" value="1984-W19" />
#
def week_field(object_name, method, options = {})
Tags::WeekField.new(object_name, method, self, options).render
end
# Returns a text_field of type "url".
#
# url_field("user", "homepage")
# # => <input id="user_homepage" name="user[homepage]" type="url" />
#
def url_field(object_name, method, options = {})
Tags::UrlField.new(object_name, method, self, options).render
end
# Returns a text_field of type "email".
#
# email_field("user", "address")
# # => <input id="user_address" name="user[address]" type="email" />
#
def email_field(object_name, method, options = {})
Tags::EmailField.new(object_name, method, self, options).render
end
# Returns an input tag of type "number".
#
# ==== Options
# * Accepts same options as number_field_tag
def number_field(object_name, method, options = {})
Tags::NumberField.new(object_name, method, self, options).render
end
# Returns an input tag of type "range".
#
# ==== Options
# * Accepts same options as range_field_tag
def range_field(object_name, method, options = {})
Tags::RangeField.new(object_name, method, self, options).render
end
private
def html_options_for_form_with(url_for_options = nil, model = nil, html: {}, local: !form_with_generates_remote_forms,
skip_enforcing_utf8: false, **options)
html_options = options.slice(:id, :class, :multipart, :method, :data).merge(html)
html_options[:method] ||= :patch if model.respond_to?(:persisted?) && model.persisted?
html_options[:enforce_utf8] = !skip_enforcing_utf8
html_options[:enctype] = "multipart/form-data" if html_options.delete(:multipart)
# The following URL is unescaped, this is just a hash of options, and it is the
# responsibility of the caller to escape all the values.
html_options[:action] = url_for(url_for_options || {})
html_options[:"accept-charset"] = "UTF-8"
html_options[:"data-remote"] = true unless local
html_options[:authenticity_token] = options.delete(:authenticity_token)
if !local && html_options[:authenticity_token].blank?
html_options[:authenticity_token] = embed_authenticity_token_in_remote_forms
end
if html_options[:authenticity_token] == true
# Include the default authenticity_token, which is only generated when it's set to nil,
# but we needed the true value to override the default of no authenticity_token on data-remote.
html_options[:authenticity_token] = nil
end
html_options.stringify_keys!
end
def instantiate_builder(record_name, record_object, options)
case record_name
when String, Symbol
object = record_object
object_name = record_name
else
object = record_name
object_name = model_name_from_record_or_class(object).param_key if object
end
builder = options[:builder] || default_form_builder_class
builder.new(object_name, object, self, options)
end
def default_form_builder_class
builder = default_form_builder || ActionView::Base.default_form_builder
builder.respond_to?(:constantize) ? builder.constantize : builder
end
end
# A +FormBuilder+ object is associated with a particular model object and
# allows you to generate fields associated with the model object. The
# +FormBuilder+ object is yielded when using +form_for+ or +fields_for+.
# For example:
#
# <%= form_for @person do |person_form| %>
# Name: <%= person_form.text_field :name %>
# Admin: <%= person_form.check_box :admin %>
# <% end %>
#
# In the above block, a +FormBuilder+ object is yielded as the
# +person_form+ variable. This allows you to generate the +text_field+
# and +check_box+ fields by specifying their eponymous methods, which
# modify the underlying template and associates the <tt>@person</tt> model object
# with the form.
#
# The +FormBuilder+ object can be thought of as serving as a proxy for the
# methods in the +FormHelper+ module. This class, however, allows you to
# call methods with the model object you are building the form for.
#
# You can create your own custom FormBuilder templates by subclassing this
# class. For example:
#
# class MyFormBuilder < ActionView::Helpers::FormBuilder
# def div_radio_button(method, tag_value, options = {})
# @template.content_tag(:div,
# @template.radio_button(
# @object_name, method, tag_value, objectify_options(options)
# )
# )
# end
# end
#
# The above code creates a new method +div_radio_button+ which wraps a div
# around the new radio button. Note that when options are passed in, you
# must call +objectify_options+ in order for the model object to get
# correctly passed to the method. If +objectify_options+ is not called,
# then the newly created helper will not be linked back to the model.
#
# The +div_radio_button+ code from above can now be used as follows:
#
# <%= form_for @person, :builder => MyFormBuilder do |f| %>
# I am a child: <%= f.div_radio_button(:admin, "child") %>
# I am an adult: <%= f.div_radio_button(:admin, "adult") %>
# <% end -%>
#
# The standard set of helper methods for form building are located in the
# +field_helpers+ class attribute.
class FormBuilder
include ModelNaming
# The methods which wrap a form helper call.
class_attribute :field_helpers, default: [
:fields_for, :fields, :label, :text_field, :password_field,
:hidden_field, :file_field, :text_area, :check_box,
:radio_button, :color_field, :search_field,
:telephone_field, :phone_field, :date_field,
:time_field, :datetime_field, :datetime_local_field,
:month_field, :week_field, :url_field, :email_field,
:number_field, :range_field
]
attr_accessor :object_name, :object, :options
attr_reader :multipart, :index
alias :multipart? :multipart
def multipart=(multipart)
@multipart = multipart
if parent_builder = @options[:parent_builder]
parent_builder.multipart = multipart
end
end
def self._to_partial_path
@_to_partial_path ||= name.demodulize.underscore.sub!(/_builder$/, "")
end
def to_partial_path
self.class._to_partial_path
end
def to_model
self
end
def initialize(object_name, object, template, options)
@nested_child_index = {}
@object_name, @object, @template, @options = object_name, object, template, options
@default_options = @options ? @options.slice(:index, :namespace, :skip_default_ids, :allow_method_names_outside_object) : {}
@default_html_options = @default_options.except(:skip_default_ids, :allow_method_names_outside_object)
convert_to_legacy_options(@options)
if @object_name.to_s.match(/\[\]$/)
if (object ||= @template.instance_variable_get("@#{Regexp.last_match.pre_match}")) && object.respond_to?(:to_param)
@auto_index = object.to_param
else
raise ArgumentError, "object[] naming but object param and @object var don't exist or don't respond to to_param: #{object.inspect}"
end
end
@multipart = nil
@index = options[:index] || options[:child_index]
end
(field_helpers - [:label, :check_box, :radio_button, :fields_for, :fields, :hidden_field, :file_field]).each do |selector|
class_eval <<-RUBY_EVAL, __FILE__, __LINE__ + 1
def #{selector}(method, options = {}) # def text_field(method, options = {})
@template.send( # @template.send(
#{selector.inspect}, # "text_field",
@object_name, # @object_name,
method, # method,
objectify_options(options)) # objectify_options(options))
end # end
RUBY_EVAL
end
# Creates a scope around a specific model object like form_for, but
# doesn't create the form tags themselves. This makes fields_for suitable
# for specifying additional model objects in the same form.
#
# Although the usage and purpose of +fields_for+ is similar to +form_for+'s,
# its method signature is slightly different. Like +form_for+, it yields
# a FormBuilder object associated with a particular model object to a block,
# and within the block allows methods to be called on the builder to
# generate fields associated with the model object. Fields may reflect
# a model object in two ways - how they are named (hence how submitted
# values appear within the +params+ hash in the controller) and what
# default values are shown when the form the fields appear in is first
# displayed. In order for both of these features to be specified independently,
# both an object name (represented by either a symbol or string) and the
# object itself can be passed to the method separately -
#
# <%= form_for @person do |person_form| %>
# First name: <%= person_form.text_field :first_name %>
# Last name : <%= person_form.text_field :last_name %>
#
# <%= fields_for :permission, @person.permission do |permission_fields| %>
# Admin? : <%= permission_fields.check_box :admin %>
# <% end %>
#
# <%= person_form.submit %>
# <% end %>
#
# In this case, the checkbox field will be represented by an HTML +input+
# tag with the +name+ attribute <tt>permission[admin]</tt>, and the submitted
# value will appear in the controller as <tt>params[:permission][:admin]</tt>.
# If <tt>@person.permission</tt> is an existing record with an attribute
# +admin+, the initial state of the checkbox when first displayed will
# reflect the value of <tt>@person.permission.admin</tt>.
#
# Often this can be simplified by passing just the name of the model
# object to +fields_for+ -
#
# <%= fields_for :permission do |permission_fields| %>
# Admin?: <%= permission_fields.check_box :admin %>
# <% end %>
#
# ...in which case, if <tt>:permission</tt> also happens to be the name of an
# instance variable <tt>@permission</tt>, the initial state of the input
# field will reflect the value of that variable's attribute <tt>@permission.admin</tt>.
#
# Alternatively, you can pass just the model object itself (if the first
# argument isn't a string or symbol +fields_for+ will realize that the
# name has been omitted) -
#
# <%= fields_for @person.permission do |permission_fields| %>
# Admin?: <%= permission_fields.check_box :admin %>
# <% end %>
#
# and +fields_for+ will derive the required name of the field from the
# _class_ of the model object, e.g. if <tt>@person.permission</tt>, is
# of class +Permission+, the field will still be named <tt>permission[admin]</tt>.
#
# Note: This also works for the methods in FormOptionsHelper and
# DateHelper that are designed to work with an object as base, like
# FormOptionsHelper#collection_select and DateHelper#datetime_select.
#
# === Nested Attributes Examples
#
# When the object belonging to the current scope has a nested attribute
# writer for a certain attribute, fields_for will yield a new scope
# for that attribute. This allows you to create forms that set or change
# the attributes of a parent object and its associations in one go.
#
# Nested attribute writers are normal setter methods named after an
# association. The most common way of defining these writers is either
# with +accepts_nested_attributes_for+ in a model definition or by
# defining a method with the proper name. For example: the attribute
# writer for the association <tt>:address</tt> is called
# <tt>address_attributes=</tt>.
#
# Whether a one-to-one or one-to-many style form builder will be yielded
# depends on whether the normal reader method returns a _single_ object
# or an _array_ of objects.
#
# ==== One-to-one
#
# Consider a Person class which returns a _single_ Address from the
# <tt>address</tt> reader method and responds to the
# <tt>address_attributes=</tt> writer method:
#
# class Person
# def address
# @address
# end
#
# def address_attributes=(attributes)
# # Process the attributes hash
# end
# end
#
# This model can now be used with a nested fields_for, like so:
#
# <%= form_for @person do |person_form| %>
# ...
# <%= person_form.fields_for :address do |address_fields| %>
# Street : <%= address_fields.text_field :street %>
# Zip code: <%= address_fields.text_field :zip_code %>
# <% end %>
# ...
# <% end %>
#
# When address is already an association on a Person you can use
# +accepts_nested_attributes_for+ to define the writer method for you:
#
# class Person < ActiveRecord::Base
# has_one :address
# accepts_nested_attributes_for :address
# end
#
# If you want to destroy the associated model through the form, you have
# to enable it first using the <tt>:allow_destroy</tt> option for
# +accepts_nested_attributes_for+:
#
# class Person < ActiveRecord::Base
# has_one :address
# accepts_nested_attributes_for :address, allow_destroy: true
# end
#
# Now, when you use a form element with the <tt>_destroy</tt> parameter,
# with a value that evaluates to +true+, you will destroy the associated
# model (eg. 1, '1', true, or 'true'):
#
# <%= form_for @person do |person_form| %>
# ...
# <%= person_form.fields_for :address do |address_fields| %>
# ...
# Delete: <%= address_fields.check_box :_destroy %>
# <% end %>
# ...
# <% end %>
#
# ==== One-to-many
#
# Consider a Person class which returns an _array_ of Project instances
# from the <tt>projects</tt> reader method and responds to the
# <tt>projects_attributes=</tt> writer method:
#
# class Person
# def projects
# [@project1, @project2]
# end
#
# def projects_attributes=(attributes)
# # Process the attributes hash
# end
# end
#
# Note that the <tt>projects_attributes=</tt> writer method is in fact
# required for fields_for to correctly identify <tt>:projects</tt> as a
# collection, and the correct indices to be set in the form markup.
#
# When projects is already an association on Person you can use
# +accepts_nested_attributes_for+ to define the writer method for you:
#
# class Person < ActiveRecord::Base
# has_many :projects
# accepts_nested_attributes_for :projects
# end
#
# This model can now be used with a nested fields_for. The block given to
# the nested fields_for call will be repeated for each instance in the
# collection:
#
# <%= form_for @person do |person_form| %>
# ...
# <%= person_form.fields_for :projects do |project_fields| %>
# <% if project_fields.object.active? %>
# Name: <%= project_fields.text_field :name %>
# <% end %>
# <% end %>
# ...
# <% end %>
#
# It's also possible to specify the instance to be used:
#
# <%= form_for @person do |person_form| %>
# ...
# <% @person.projects.each do |project| %>
# <% if project.active? %>
# <%= person_form.fields_for :projects, project do |project_fields| %>
# Name: <%= project_fields.text_field :name %>
# <% end %>
# <% end %>
# <% end %>
# ...
# <% end %>
#
# Or a collection to be used:
#
# <%= form_for @person do |person_form| %>
# ...
# <%= person_form.fields_for :projects, @active_projects do |project_fields| %>
# Name: <%= project_fields.text_field :name %>
# <% end %>
# ...
# <% end %>
#
# If you want to destroy any of the associated models through the
# form, you have to enable it first using the <tt>:allow_destroy</tt>
# option for +accepts_nested_attributes_for+:
#
# class Person < ActiveRecord::Base
# has_many :projects
# accepts_nested_attributes_for :projects, allow_destroy: true
# end
#
# This will allow you to specify which models to destroy in the
# attributes hash by adding a form element for the <tt>_destroy</tt>
# parameter with a value that evaluates to +true+
# (eg. 1, '1', true, or 'true'):
#
# <%= form_for @person do |person_form| %>
# ...
# <%= person_form.fields_for :projects do |project_fields| %>
# Delete: <%= project_fields.check_box :_destroy %>
# <% end %>
# ...
# <% end %>
#
# When a collection is used you might want to know the index of each
# object into the array. For this purpose, the <tt>index</tt> method
# is available in the FormBuilder object.
#
# <%= form_for @person do |person_form| %>
# ...
# <%= person_form.fields_for :projects do |project_fields| %>
# Project #<%= project_fields.index %>
# ...
# <% end %>
# ...
# <% end %>
#
# Note that fields_for will automatically generate a hidden field
# to store the ID of the record. There are circumstances where this
# hidden field is not needed and you can pass <tt>include_id: false</tt>
# to prevent fields_for from rendering it automatically.
def fields_for(record_name, record_object = nil, fields_options = {}, &block)
fields_options, record_object = record_object, nil if record_object.is_a?(Hash) && record_object.extractable_options?
fields_options[:builder] ||= options[:builder]
fields_options[:namespace] = options[:namespace]
fields_options[:parent_builder] = self
case record_name
when String, Symbol
if nested_attributes_association?(record_name)
return fields_for_with_nested_attributes(record_name, record_object, fields_options, block)
end
else
record_object = record_name.is_a?(Array) ? record_name.last : record_name
record_name = model_name_from_record_or_class(record_object).param_key
end
object_name = @object_name
index = if options.has_key?(:index)
options[:index]
elsif defined?(@auto_index)
object_name = object_name.to_s.sub(/\[\]$/, "")
@auto_index
end
record_name = if index
"#{object_name}[#{index}][#{record_name}]"
elsif record_name.to_s.end_with?("[]")
record_name = record_name.to_s.sub(/(.*)\[\]$/, "[\\1][#{record_object.id}]")
"#{object_name}#{record_name}"
else
"#{object_name}[#{record_name}]"
end
fields_options[:child_index] = index
@template.fields_for(record_name, record_object, fields_options, &block)
end
# See the docs for the <tt>ActionView::FormHelper.fields</tt> helper method.
def fields(scope = nil, model: nil, **options, &block)
options[:allow_method_names_outside_object] = true
options[:skip_default_ids] = !FormHelper.form_with_generates_ids
convert_to_legacy_options(options)
fields_for(scope || model, model, **options, &block)
end
# Returns a label tag tailored for labelling an input field for a specified attribute (identified by +method+) on an object
# assigned to the template (identified by +object+). The text of label will default to the attribute name unless a translation
# is found in the current I18n locale (through helpers.label.<modelname>.<attribute>) or you specify it explicitly.
# Additional options on the label tag can be passed as a hash with +options+. These options will be tagged
# onto the HTML as an HTML element attribute as in the example shown, except for the <tt>:value</tt> option, which is designed to
# target labels for radio_button tags (where the value is used in the ID of the input tag).
#
# ==== Examples
# label(:title)
# # => <label for="post_title">Title</label>
#
# You can localize your labels based on model and attribute names.
# For example you can define the following in your locale (e.g. en.yml)
#
# helpers:
# label:
# post:
# body: "Write your entire text here"
#
# Which then will result in
#
# label(:body)
# # => <label for="post_body">Write your entire text here</label>
#
# Localization can also be based purely on the translation of the attribute-name
# (if you are using ActiveRecord):
#
# activerecord:
# attributes:
# post:
# cost: "Total cost"
#
# label(:cost)
# # => <label for="post_cost">Total cost</label>
#
# label(:title, "A short title")
# # => <label for="post_title">A short title</label>
#
# label(:title, "A short title", class: "title_label")
# # => <label for="post_title" class="title_label">A short title</label>
#
# label(:privacy, "Public Post", value: "public")
# # => <label for="post_privacy_public">Public Post</label>
#
# label(:terms) do
# raw('Accept <a href="/terms">Terms</a>.')
# end
# # => <label for="post_terms">Accept <a href="/terms">Terms</a>.</label>
def label(method, text = nil, options = {}, &block)
@template.label(@object_name, method, text, objectify_options(options), &block)
end
# Returns a checkbox tag tailored for accessing a specified attribute (identified by +method+) on an object
# assigned to the template (identified by +object+). This object must be an instance object (@object) and not a local object.
# It's intended that +method+ returns an integer and if that integer is above zero, then the checkbox is checked.
# Additional options on the input tag can be passed as a hash with +options+. The +checked_value+ defaults to 1
# while the default +unchecked_value+ is set to 0 which is convenient for boolean values.
#
# ==== Gotcha
#
# The HTML specification says unchecked check boxes are not successful, and
# thus web browsers do not send them. Unfortunately this introduces a gotcha:
# if an +Invoice+ model has a +paid+ flag, and in the form that edits a paid
# invoice the user unchecks its check box, no +paid+ parameter is sent. So,
# any mass-assignment idiom like
#
# @invoice.update(params[:invoice])
#
# wouldn't update the flag.
#
# To prevent this the helper generates an auxiliary hidden field before
# the very check box. The hidden field has the same name and its
# attributes mimic an unchecked check box.
#
# This way, the client either sends only the hidden field (representing
# the check box is unchecked), or both fields. Since the HTML specification
# says key/value pairs have to be sent in the same order they appear in the
# form, and parameters extraction gets the last occurrence of any repeated
# key in the query string, that works for ordinary forms.
#
# Unfortunately that workaround does not work when the check box goes
# within an array-like parameter, as in
#
# <%= fields_for "project[invoice_attributes][]", invoice, index: nil do |form| %>
# <%= form.check_box :paid %>
# ...
# <% end %>
#
# because parameter name repetition is precisely what Rails seeks to distinguish
# the elements of the array. For each item with a checked check box you
# get an extra ghost item with only that attribute, assigned to "0".
#
# In that case it is preferable to either use +check_box_tag+ or to use
# hashes instead of arrays.
#
# # Let's say that @post.validated? is 1:
# check_box("validated")
# # => <input name="post[validated]" type="hidden" value="0" />
# # <input checked="checked" type="checkbox" id="post_validated" name="post[validated]" value="1" />
#
# # Let's say that @puppy.gooddog is "no":
# check_box("gooddog", {}, "yes", "no")
# # => <input name="puppy[gooddog]" type="hidden" value="no" />
# # <input type="checkbox" id="puppy_gooddog" name="puppy[gooddog]" value="yes" />
#
# # Let's say that @eula.accepted is "no":
# check_box("accepted", { class: 'eula_check' }, "yes", "no")
# # => <input name="eula[accepted]" type="hidden" value="no" />
# # <input type="checkbox" class="eula_check" id="eula_accepted" name="eula[accepted]" value="yes" />
def check_box(method, options = {}, checked_value = "1", unchecked_value = "0")
@template.check_box(@object_name, method, objectify_options(options), checked_value, unchecked_value)
end
# Returns a radio button tag for accessing a specified attribute (identified by +method+) on an object
# assigned to the template (identified by +object+). If the current value of +method+ is +tag_value+ the
# radio button will be checked.
#
# To force the radio button to be checked pass <tt>checked: true</tt> in the
# +options+ hash. You may pass HTML options there as well.
#
# # Let's say that @post.category returns "rails":
# radio_button("category", "rails")
# radio_button("category", "java")
# # => <input type="radio" id="post_category_rails" name="post[category]" value="rails" checked="checked" />
# # <input type="radio" id="post_category_java" name="post[category]" value="java" />
#
# # Let's say that @user.receive_newsletter returns "no":
# radio_button("receive_newsletter", "yes")
# radio_button("receive_newsletter", "no")
# # => <input type="radio" id="user_receive_newsletter_yes" name="user[receive_newsletter]" value="yes" />
# # <input type="radio" id="user_receive_newsletter_no" name="user[receive_newsletter]" value="no" checked="checked" />
def radio_button(method, tag_value, options = {})
@template.radio_button(@object_name, method, tag_value, objectify_options(options))
end
# Returns a hidden input tag tailored for accessing a specified attribute (identified by +method+) on an object
# assigned to the template (identified by +object+). Additional options on the input tag can be passed as a
# hash with +options+. These options will be tagged onto the HTML as an HTML element attribute as in the example
# shown.
#
# ==== Examples
# # Let's say that @signup.pass_confirm returns true:
# hidden_field(:pass_confirm)
# # => <input type="hidden" id="signup_pass_confirm" name="signup[pass_confirm]" value="true" />
#
# # Let's say that @post.tag_list returns "blog, ruby":
# hidden_field(:tag_list)
# # => <input type="hidden" id="post_tag_list" name="post[tag_list]" value="blog, ruby" />
#
# # Let's say that @user.token returns "abcde":
# hidden_field(:token)
# # => <input type="hidden" id="user_token" name="user[token]" value="abcde" />
#
def hidden_field(method, options = {})
@emitted_hidden_id = true if method == :id
@template.hidden_field(@object_name, method, objectify_options(options))
end
# Returns a file upload input tag tailored for accessing a specified attribute (identified by +method+) on an object
# assigned to the template (identified by +object+). Additional options on the input tag can be passed as a
# hash with +options+. These options will be tagged onto the HTML as an HTML element attribute as in the example
# shown.
#
# Using this method inside a +form_for+ block will set the enclosing form's encoding to <tt>multipart/form-data</tt>.
#
# ==== Options
# * Creates standard HTML attributes for the tag.
# * <tt>:disabled</tt> - If set to true, the user will not be able to use this input.
# * <tt>:multiple</tt> - If set to true, *in most updated browsers* the user will be allowed to select multiple files.
# * <tt>:accept</tt> - If set to one or multiple mime-types, the user will be suggested a filter when choosing a file. You still need to set up model validations.
#
# ==== Examples
# # Let's say that @user has avatar:
# file_field(:avatar)
# # => <input type="file" id="user_avatar" name="user[avatar]" />
#
# # Let's say that @post has image:
# file_field(:image, :multiple => true)
# # => <input type="file" id="post_image" name="post[image][]" multiple="multiple" />
#
# # Let's say that @post has attached:
# file_field(:attached, accept: 'text/html')
# # => <input accept="text/html" type="file" id="post_attached" name="post[attached]" />
#
# # Let's say that @post has image:
# file_field(:image, accept: 'image/png,image/gif,image/jpeg')
# # => <input type="file" id="post_image" name="post[image]" accept="image/png,image/gif,image/jpeg" />
#
# # Let's say that @attachment has file:
# file_field(:file, class: 'file_input')
# # => <input type="file" id="attachment_file" name="attachment[file]" class="file_input" />
def file_field(method, options = {})
self.multipart = true
@template.file_field(@object_name, method, objectify_options(options))
end
# Add the submit button for the given form. When no value is given, it checks
# if the object is a new resource or not to create the proper label:
#
# <%= form_for @post do |f| %>
# <%= f.submit %>
# <% end %>
#
# In the example above, if <tt>@post</tt> is a new record, it will use "Create Post" as
# submit button label; otherwise, it uses "Update Post".
#
# Those labels can be customized using I18n under the +helpers.submit+ key and using
# <tt>%{model}</tt> for translation interpolation:
#
# en:
# helpers:
# submit:
# create: "Create a %{model}"
# update: "Confirm changes to %{model}"
#
# It also searches for a key specific to the given object:
#
# en:
# helpers:
# submit:
# post:
# create: "Add %{model}"
#
def submit(value = nil, options = {})
value, options = nil, value if value.is_a?(Hash)
value ||= submit_default_value
@template.submit_tag(value, options)
end
# Add the submit button for the given form. When no value is given, it checks
# if the object is a new resource or not to create the proper label:
#
# <%= form_for @post do |f| %>
# <%= f.button %>
# <% end %>
#
# In the example above, if <tt>@post</tt> is a new record, it will use "Create Post" as
# button label; otherwise, it uses "Update Post".
#
# Those labels can be customized using I18n under the +helpers.submit+ key
# (the same as submit helper) and using <tt>%{model}</tt> for translation interpolation:
#
# en:
# helpers:
# submit:
# create: "Create a %{model}"
# update: "Confirm changes to %{model}"
#
# It also searches for a key specific to the given object:
#
# en:
# helpers:
# submit:
# post:
# create: "Add %{model}"
#
# ==== Examples
# button("Create post")
# # => <button name='button' type='submit'>Create post</button>
#
# button do
# content_tag(:strong, 'Ask me!')
# end
# # => <button name='button' type='submit'>
# # <strong>Ask me!</strong>
# # </button>
#
def button(value = nil, options = {}, &block)
value, options = nil, value if value.is_a?(Hash)
value ||= submit_default_value
@template.button_tag(value, options, &block)
end
def emitted_hidden_id?
@emitted_hidden_id ||= nil
end
private
def objectify_options(options)
@default_options.merge(options.merge(object: @object))
end
def submit_default_value
object = convert_to_model(@object)
key = object ? (object.persisted? ? :update : :create) : :submit
model = if object.respond_to?(:model_name)
object.model_name.human
else
@object_name.to_s.humanize
end
defaults = []
defaults << :"helpers.submit.#{object_name}.#{key}"
defaults << :"helpers.submit.#{key}"
defaults << "#{key.to_s.humanize} #{model}"
I18n.t(defaults.shift, model: model, default: defaults)
end
def nested_attributes_association?(association_name)
@object.respond_to?("#{association_name}_attributes=")
end
def fields_for_with_nested_attributes(association_name, association, options, block)
name = "#{object_name}[#{association_name}_attributes]"
association = convert_to_model(association)
if association.respond_to?(:persisted?)
association = [association] if @object.send(association_name).respond_to?(:to_ary)
elsif !association.respond_to?(:to_ary)
association = @object.send(association_name)
end
if association.respond_to?(:to_ary)
explicit_child_index = options[:child_index]
output = ActiveSupport::SafeBuffer.new
association.each do |child|
if explicit_child_index
options[:child_index] = explicit_child_index.call if explicit_child_index.respond_to?(:call)
else
options[:child_index] = nested_child_index(name)
end
output << fields_for_nested_model("#{name}[#{options[:child_index]}]", child, options, block)
end
output
elsif association
fields_for_nested_model(name, association, options, block)
end
end
def fields_for_nested_model(name, object, fields_options, block)
object = convert_to_model(object)
emit_hidden_id = object.persisted? && fields_options.fetch(:include_id) {
options.fetch(:include_id, true)
}
@template.fields_for(name, object, fields_options) do |f|
output = @template.capture(f, &block)
output.concat f.hidden_field(:id) if output && emit_hidden_id && !f.emitted_hidden_id?
output
end
end
def nested_child_index(name)
@nested_child_index[name] ||= -1
@nested_child_index[name] += 1
end
def convert_to_legacy_options(options)
if options.key?(:skip_id)
options[:include_id] = !options.delete(:skip_id)
end
end
end
end
ActiveSupport.on_load(:action_view) do
cattr_accessor :default_form_builder, instance_writer: false, instance_reader: false, default: ::ActionView::Helpers::FormBuilder
end
end
| 45.43627 | 194 | 0.605234 |
33cd6ff3d377018d982e97ac9b79bca7f77fd0e6 | 795 | require 'rails_helper'
RSpec.describe NicoApi::Mylist::Mylist, type: :model do
describe 'list' do
let(:session){ FactoryGirl.build :session }
let(:json){ File.read('spec/fixtures/nico_api_mylist/ok.json') }
before do
stub_request(:get, "http://www.nicovideo.jp/api/mylist/list?group_id=12")
.with(headers: {
'Cookie'=> self.session.cookie
})
.to_return(status: 200, body: json)
end
subject { NicoApi::Mylist::Mylist.new(self.session, 12).list }
it 'should be mylist items' do
is_expected.to eq JSON.parse(self.json)['mylistitem']
end
context 'when occured errors' do
let(:json){ File.read('spec/fixtures/nico_api_mylist/error.json') }
it { is_expected.to be_nil }
end
end
end
| 28.392857 | 79 | 0.63522 |
397b5f6e77678d6beca8d0d1bb11e68ee57c9785 | 3,114 | require "insta/version"
require 'net/http'
require 'uri'
require 'json'
module Insta
class Error < StandardError; end
class Client
attr_accessor :redirect_uri, :client_id, :client_secret, :scope
def initialize(options = {})
@redirect_uri = options[:redirect_uri]
@client_id = options[:client_id]
@client_secret = options[:client_secret]
@scope = options[:scope] || 'user_profile,user_media'
end
def auth_url
"https://api.instagram.com/oauth/authorize?client_id=#{client_id}&redirect_uri=#{redirect_uri}&scope=#{scope}&response_type=code"
end
def access_token(code = '')
uri = URI.parse("https://api.instagram.com/oauth/access_token")
request = Net::HTTP::Post.new(uri)
request.set_form_data(
"client_id" => client_id,
"client_secret" => client_secret,
"code" => code,
"grant_type" => "authorization_code",
"redirect_uri" => redirect_uri,
)
req_options = {
use_ssl: uri.scheme == "https",
}
response = Net::HTTP.start(uri.hostname, uri.port, req_options) do |http|
http.request(request)
end
response = JSON.parse(response.body)
OpenStruct.new(response)
end
def long_lived_access_token(access_token)
url = "https://graph.instagram.com/access_token?grant_type=ig_exchange_token&client_secret=#{client_secret}&access_token=#{access_token}"
uri = URI.parse(url)
request = Net::HTTP::Get.new(uri)
req_options = {
use_ssl: uri.scheme == "https",
}
response = Net::HTTP.start(uri.hostname, uri.port, req_options) do |http|
http.request(request)
end
response = JSON.parse(response.body)
OpenStruct.new(response)
end
end
class API
attr_accessor :access_token, :next_url
def initialize(access_token)
@access_token = access_token
@next_url = nil
end
def me
url = "https://graph.instagram.com/me?fields=account_type,media_count,username,id&access_token=#{access_token}"
get(url)
end
def media(limit = 100)
url = "https://graph.instagram.com/me/media?fields=id,media_type,caption,permalink,thumbnail_url,media_url,username,timestamp&access_token=#{access_token}&limit=#{limit}"
response = get(url)
puts response.dig('paging', 'next')
@next_url = response.dig('paging', 'next') unless response.dig('paging', 'next').nil?
response
end
def next_page
return {} if next_url.nil?
response = get(next_url)
if response.dig('paging', 'next').nil?
@next_url = nil
else
@next_url = response.dig('paging', 'next')
end
response
end
private
def get(url)
uri = URI.parse(url)
request = Net::HTTP::Get.new(uri)
req_options = {
use_ssl: uri.scheme == "https",
}
response = Net::HTTP.start(uri.hostname, uri.port, req_options) do |http|
http.request(request)
end
response = JSON.parse(response.body)
OpenStruct.new(response)
end
end
end
| 29.377358 | 176 | 0.634875 |
084419a1fc95e99b59d4d959d7fe34d66b793692 | 1,309 | $:.push File.expand_path("lib", __dir__)
# Maintain your gem's version:
require "quick_search/pamphlets/version"
# Describe your gem and declare its dependencies:
Gem::Specification.new do |spec|
spec.name = "quick_search-pamphlets"
spec.version = QuickSearch::Pamphlets::VERSION
spec.authors = ["Gregory Wiedeman"]
spec.email = ["[email protected]"]
spec.homepage = "https://archives.albany.edu"
spec.summary = "Searcher for the Politcal Pamphlets Collections"
spec.description = "Plugin for NCSU QuickSearch bento-style search results app that searches a blacklight app that discovers materals from the poltical pamphlets collections"
spec.license = "MIT"
# Prevent pushing this gem to RubyGems.org. To allow pushes either set the 'allowed_push_host'
# to allow pushing to a single host or delete this section to allow pushing to any host.
if spec.respond_to?(:metadata)
spec.metadata["allowed_push_host"] = "TODO: Set to 'http://mygemserver.com'"
else
raise "RubyGems 2.0 or newer is required to protect against " \
"public gem pushes."
end
spec.files = Dir["{app,config,db,lib}/**/*", "MIT-LICENSE", "Rakefile", "README.md"]
spec.add_dependency "rails", "~> 5.2.6"
spec.add_development_dependency "sqlite3"
end
| 40.90625 | 176 | 0.717341 |
5d450a03cbfc0acbe3e75f0d0bb048b9fd242406 | 1,235 | # This file is auto-generated by the code_generator (one-time action)
#
# Cookbook Name:: smbios
# Spec:: default
#
# Copyright:: 2018, The Authors, All Rights Reserved.
require 'spec_helper'
describe 'smbios::default' do
context 'When all attributes are default, on centos 6.9' do
let(:chef_run) do
runner = ChefSpec::SoloRunner.new(
platform: 'centos',
version: '6.9',
)
runner.converge(described_recipe)
end
it 'converges successfully' do
expect { chef_run }.to_not raise_error
end
end
context 'When all attributes are default, on centos 7.4.1708' do
let(:chef_run) do
runner = ChefSpec::SoloRunner.new(
platform: 'centos',
version: '7.4.1708',
)
runner.converge(described_recipe)
end
it 'converges successfully' do
expect { chef_run }.to_not raise_error
end
end
context 'When all attributes are default, on windows 6.3.9600' do
let(:chef_run) do
runner = ChefSpec::SoloRunner.new(
platform: 'windows',
version: '2012R2',
)
runner.converge(described_recipe)
end
it 'converges successfully' do
expect { chef_run }.to_not raise_error
end
end
end
| 24.215686 | 69 | 0.646154 |
ab020e2d70424d902515ccac4e738b1c231045e2 | 352 | ENV["RAILS_ENV"] = 'test'
require File.expand_path("../dummy/config/environment.rb", __FILE__)
require 'rspec/rails'
require 'capybara/rspec'
require 'tempfile'
require 'pry'
Dir["#{File.dirname(__FILE__)}/factories/**/*.rb"].each { |f| require f }
RSpec.configure do |config|
config.mock_with :rspec
config.use_transactional_fixtures = true
end
| 25.142857 | 73 | 0.735795 |
116a2abb458f49a116886344f913019a9511e421 | 979 | module SUNAT
class Party
include Model
property :name, String
property :physical_location, PhysicalLocation # only for tacna and only for receipts. sunat dixit
property :party_legal_entity, PartyLegalEntity
property :postal_addresses, [PostalAddress]
validates :party_legal_entity, existence: true
validates :postal_addresses, existence: true, not_empty: true
def initialize(*args)
super(*args)
self.postal_addresses ||= []
end
def build_xml(xml)
xml['cac'].Party do
if name.present?
xml['cac'].PartyName do
xml['cbc'].Name name
end
end
postal_addresses.each do |address|
address.build_xml xml
end
party_legal_entity.build_xml xml
if physical_location.present?
physical_location.build_xml xml
end
end
end
end
end | 25.102564 | 106 | 0.592441 |
626bd83cf9e07a2fe2838e0735d2f9ef31bed6ce | 2,960 | # -*- ruby -*-
# encoding: utf-8
require_relative 'lib/introrb/foreignc/version'
Gem::Specification.new do |s|
gemfiles = gemfiles = (File.exist?('Manifest.txt') ? (File.read('Manifest.txt').split(/\r?\n\r?/) rescue nil) : Dir.glob('{lib/**/*,ext/**/*.i,resources/*}', File::FNM_DOTMATCH)) # + Dir.glob('{*.gemspec,.editorconfig,exclude.lst,.*ignore,.document,.rdoc_options,.rspec,.yardopts,*.sh,Gemfile,*akefile,README*,test/**/*,spec/**/*}', File::FNM_DOTMATCH)
# gemfiles = `git ls-files`.split # [git ls-files | hg manifest -r default | svn ls -R]
## cmd w/ zip: zip -q -x @exclude.lst -r - . | unzip -Z -1 -
## cmd w/ tar: tar -X exclude.lst -cf - . | tar -tf - | sed "s|^./||"
# gemfiles = (proc {
# require 'open3'
# out, err, st = Open3.capture3('zip -q -x @exclude.lst -r - . | unzip -Z -1 -')
# out.split.reject{|f| File.directory? f} }).call
# gemfiles = `tar -X exclude.lst -cf - . | tar -tf - | sed "s|^./||"`.split.reject{
# |f| File.directory? f}
s.name = 'introrb-foreignc'
s.version = Introrb::Foreignc::VERSION
s.summary = 'FFI sub-package for Ruby Intro examples project.'
s.authors = ['thebridge0491']
s.files = gemfiles.reject{|f| f.match(%r{^(test|spec)/})}
s.licenses = ['Apache-2.0']
s.description = 'FFI sub-package for Ruby Intro examples project.'
s.email = ['[email protected]']
s.homepage = 'https://www.bitbucket.org/thebridge0491/introrb'
# s.metadata = { 'bug_tracker_uri' => "#{s.homepage}/issues",
# 'homepage_uri' => s.homepage, 'source_code_uri' => s.homepage
# } if s.respond_to? :metadata=
s.test_files = gemfiles.select{|f| f.match(%r{^(test|spec)/})} if
s.respond_to? :test_files=
# s.require_paths = ['lib']
# s.bindir = 'bin'
s.executables = Dir.glob("#{s.bindir}/*").map{|f|
File.basename f}.reject{|f| f.match(%r{^(console|setup)$})}
s.extensions = Dir.glob('ext/**/extconf.rb')
s.extra_rdoc_files = Dir.glob('{LICENSE,README*}')
# s.rdoc_options = ['--main', 'README.txt']
s.required_ruby_version = Gem::Requirement.new('>= 2.7') if
s.respond_to? :required_ruby_version=
s.required_rubygems_version = Gem::Requirement.new('>= 3.0') if
s.respond_to? :required_rubygems_version=
s.platform = Gem::Platform::RUBY
## (trusted source) gem cert --add $HOME/.pki/publish_crls/demoCA/chain.crt
# s.cert_chain = ["#{ENV['HOME']}/.pki/paired/codesign.pem"]
# s.signing_key = "#{ENV['HOME']}/.pki/paired/codesign.pem"
# s.date = '2013-08-01' # Time.now.strftime('%Y-%m-%d')
{'bundler' => '>= 2.3', 'rake' => '>= 13.0', 'rdoc' => '>= 6.3',
'yard' => '>= 0.9', 'rspec' => '>= 3.10', 'minitest' => '>= 5.14',
'simplecov' => '>= 0.21', 'rubocop' => '>= 1.24',
'rake-compiler' => '>= 1.1', 'introrb-util' => '>= 0.1'}.each do |depn, ver|
s.add_development_dependency depn, ver
end
{'ffi' => '>= 1.14'
}.each do |depn, ver|
s.add_runtime_dependency depn, ver
end
end
| 44.848485 | 354 | 0.608784 |
d5328d15e7ca45ff89afc1dc055841d5007174bf | 4,295 | module RedisOrm
module Associations
module HasOne
# user.avatars => user:1:avatars => [1, 22, 234] => Avatar.find([1, 22, 234])
# *options* is a hash and can hold:
# *:as* key
# *:dependant* key: either *destroy* or *nullify* (default)
def has_one(foreign_model, options = {})
class_associations = class_variable_get(:"@@associations")
class_associations[model_name] << {:type => :has_one, :foreign_model => foreign_model, :options => options}
foreign_model_name = if options[:as]
options[:as].to_sym
else
foreign_model.to_sym
end
if options[:index]
class_variable_get(:"@@indices")[model_name] << {:name => foreign_model_name, :options => {:reference => true}}
end
define_method foreign_model_name do
foreign_model.to_s.camelize.constantize.find($redis.get "#{model_name}:#{@id}:#{foreign_model_name}")
end
# profile = Profile.create :title => 'test'
# user.profile = profile => user:23:profile => 1
define_method "#{foreign_model_name}=" do |assoc_with_record|
# we need to store this to clear old associations later
old_assoc = self.send(foreign_model_name)
reference_key = "#{model_name}:#{id}:#{foreign_model_name}"
if assoc_with_record.nil?
$redis.del(reference_key)
elsif assoc_with_record.model_name == foreign_model.to_s
$redis.set(reference_key, assoc_with_record.id)
set_expire_on_reference_key(reference_key)
else
raise TypeMismatchError
end
# handle indices for references
self.get_indices.select{|index| index[:options][:reference]}.each do |index|
# delete old reference that points to the old associated record
if !old_assoc.nil?
prepared_index = [self.model_name, index[:name], old_assoc.id].join(':')
prepared_index.downcase! if index[:options][:case_insensitive]
if index[:options][:unique]
$redis.del(prepared_index, id)
else
$redis.zrem(prepared_index, id)
end
end
# if new associated record is nil then skip to next index (since old associated record was already unreferenced)
next if assoc_with_record.nil?
prepared_index = [self.model_name, index[:name], assoc_with_record.id].join(':')
prepared_index.downcase! if index[:options][:case_insensitive]
if index[:options][:unique]
$redis.set(prepared_index, id)
else
$redis.zadd(prepared_index, Time.now.to_f, id)
end
end
if !options[:as]
if assoc_with_record.nil?
# remove old assoc
$redis.zrem("#{old_assoc.model_name}:#{old_assoc.id}:#{model_name.to_s.pluralize}", id) if old_assoc
else
# check whether *assoc_with_record* object has *belongs_to* declaration and TODO it states *self.model_name* and there is no record yet from the *assoc_with_record*'s side (in order not to provoke recursion)
if class_associations[assoc_with_record.model_name].detect{|h| [:belongs_to, :has_one].include?(h[:type]) && h[:foreign_model] == model_name.to_sym} && assoc_with_record.send(model_name.to_sym).nil?
# old association is being rewritten here automatically so we don't have to worry about it
assoc_with_record.send("#{model_name}=", self)
elsif class_associations[assoc_with_record.model_name].detect{|h| :has_many == h[:type] && h[:foreign_models] == model_name.to_s.pluralize.to_sym} && !$redis.zrank("#{assoc_with_record.model_name}:#{assoc_with_record.id}:#{model_name.pluralize}", self.id)
# remove old assoc
$redis.zrem("#{old_assoc.model_name}:#{old_assoc.id}:#{model_name.to_s.pluralize}", id) if old_assoc
# create/add new ones
assoc_with_record.send(model_name.pluralize.to_sym).send(:"<<", self)
end
end
end
end
end
end
end
end
| 46.684783 | 269 | 0.607916 |
3948e53bc177d55e8acb2cd064abd624c249562a | 5,890 | # frozen_string_literal: true
require 'spec_helper'
describe Gitlab::ProjectTemplate do
describe '.all' do
it 'returns a all templates' do
expected = [
described_class.new('rails', 'Ruby on Rails', 'Includes an MVC structure, .gitignore, Gemfile, and more great stuff', 'https://gitlab.com/gitlab-org/project-templates/rails'),
described_class.new('spring', 'Spring', 'Includes an MVC structure, .gitignore, Gemfile, and more great stuff', 'https://gitlab.com/gitlab-org/project-templates/spring'),
described_class.new('express', 'NodeJS Express', 'Includes an MVC structure, .gitignore, Gemfile, and more great stuff', 'https://gitlab.com/gitlab-org/project-templates/express'),
described_class.new('iosswift', 'iOS (Swift)', 'A ready-to-go template for use with iOS Swift apps.', 'https://gitlab.com/gitlab-org/project-templates/iosswift'),
described_class.new('dotnetcore', '.NET Core', 'A .NET Core console application template, customizable for any .NET Core project', 'https://gitlab.com/gitlab-org/project-templates/dotnetcore'),
described_class.new('android', 'Android', 'A ready-to-go template for use with Android apps.', 'https://gitlab.com/gitlab-org/project-templates/android'),
described_class.new('gomicro', 'Go Micro', 'Go Micro is a framework for micro service development.', 'https://gitlab.com/gitlab-org/project-templates/go-micro'),
described_class.new('gatsby', 'Pages/Gatsby', 'Everything you need to get started using a Gatsby site.', 'https://gitlab.com/pages/gatsby'),
described_class.new('hugo', 'Pages/Hugo', 'Everything you need to get started using a Hugo Pages site.', 'https://gitlab.com/pages/hugo'),
described_class.new('jekyll', 'Pages/Jekyll', 'Everything you need to get started using a Jekyll Pages site.', 'https://gitlab.com/pages/jekyll'),
described_class.new('plainhtml', 'Pages/Plain HTML', 'Everything you need to get started using a plain HTML Pages site.', 'https://gitlab.com/pages/plain-html'),
described_class.new('gitbook', 'Pages/GitBook', 'Everything you need to get started using a GitBook Pages site.', 'https://gitlab.com/pages/gitbook'),
described_class.new('hexo', 'Pages/Hexo', 'Everything you need to get started using a Hexo Pages site.', 'https://gitlab.com/pages/hexo'),
described_class.new('nfhugo', 'Netlify/Hugo', _('A Hugo site that uses Netlify for CI/CD instead of GitLab, but still with all the other great GitLab features.'), 'https://gitlab.com/pages/nfhugo'),
described_class.new('nfjekyll', 'Netlify/Jekyll', _('A Jekyll site that uses Netlify for CI/CD instead of GitLab, but still with all the other great GitLab features.'), 'https://gitlab.com/pages/nfjekyll'),
described_class.new('nfplainhtml', 'Netlify/Plain HTML', _('A plain HTML site that uses Netlify for CI/CD instead of GitLab, but still with all the other great GitLab features.'), 'https://gitlab.com/pages/nfplain-html'),
described_class.new('nfgitbook', 'Netlify/GitBook', _('A GitBook site that uses Netlify for CI/CD instead of GitLab, but still with all the other great GitLab features.'), 'https://gitlab.com/pages/nfgitbook'),
described_class.new('nfhexo', 'Netlify/Hexo', _('A Hexo site that uses Netlify for CI/CD instead of GitLab, but still with all the other great GitLab features.'), 'https://gitlab.com/pages/nfhexo'),
described_class.new('salesforcedx', 'SalesforceDX', _('A project boilerplate for Salesforce App development with Salesforce Developer tools.'), 'https://gitlab.com/gitlab-org/project-templates/salesforcedx'),
described_class.new('serverless_framework', 'Serverless Framework/JS', _('A basic page and serverless function that uses AWS Lambda, AWS API Gateway, and GitLab Pages'), 'https://gitlab.com/gitlab-org/project-templates/serverless-framework', 'illustrations/logos/serverless_framework.svg')
]
expect(described_class.all).to be_an(Array)
expect(described_class.all).to eq(expected)
end
end
describe '#project_path' do
subject { described_class.new('name', 'title', 'description', 'https://gitlab.com/some/project/path').project_path }
it { is_expected.to eq 'some/project/path' }
end
describe '#uri_encoded_project_path' do
subject { described_class.new('name', 'title', 'description', 'https://gitlab.com/some/project/path').uri_encoded_project_path }
it { is_expected.to eq 'some%2Fproject%2Fpath' }
end
describe '.find' do
subject { described_class.find(query) }
context 'when there is a match' do
let(:query) { :rails }
it { is_expected.to be_a(described_class) }
end
context 'when there is no match' do
let(:query) { 'no-match' }
it { is_expected.to be(nil) }
end
end
describe '.archive_directory' do
subject { described_class.archive_directory }
it { is_expected.to be_a Pathname }
end
describe 'instance methods' do
subject { described_class.new('phoenix', 'Phoenix Framework', 'Phoenix description', 'link-to-template') }
it { is_expected.to respond_to(:logo, :file, :archive_path) }
end
describe 'validate all templates' do
let_it_be(:admin) { create(:admin) }
described_class.all.each do |template|
it "#{template.name} has a valid archive" do
archive = template.archive_path
expect(File.exist?(archive)).to be(true)
end
context 'with valid parameters' do
it 'can be imported' do
params = {
template_name: template.name,
namespace_id: admin.namespace.id,
path: template.name
}
project = Projects::CreateFromTemplateService.new(admin, params).execute
expect(project).to be_valid
expect(project).to be_persisted
end
end
end
end
end
| 57.184466 | 297 | 0.701019 |
28f2fcdee1472cc6944539dd19af3892530e40ac | 86 | RSpec.describe "21" do
it do
sleep 21 / 100.0
expect(21).to eq 21
end
end
| 12.285714 | 23 | 0.604651 |
08a9213e00b0b2b33c668c66ea7df16a731489be | 2,395 | # frozen_string_literal: true
require "spec_helper"
require "rubygems/security"
# unfortunately, testing signed gems with a provided CA is extremely difficult
# as 'gem cert' is currently the only way to add CAs to the system.
describe "policies with unsigned gems" do
before do
build_security_repo
gemfile <<-G
source "file://#{security_repo}"
gem "rack"
gem "signed_gem"
G
end
it "will work after you try to deploy without a lock" do
bundle "install --deployment"
bundle :install
expect(exitstatus).to eq(0) if exitstatus
should_be_installed "rack 1.0", "signed_gem 1.0"
end
it "will fail when given invalid security policy" do
bundle "install --trust-policy=InvalidPolicyName"
expect(out).to include("Rubygems doesn't know about trust policy")
end
it "will fail with High Security setting due to presence of unsigned gem" do
bundle "install --trust-policy=HighSecurity"
expect(out).to include("security policy didn't allow")
end
# This spec will fail on Rubygems 2 rc1 due to a bug in policy.rb. the bug is fixed in rc3.
it "will fail with Medium Security setting due to presence of unsigned gem", :unless => ENV["RGV"] == "v2.0.0.rc.1" do
bundle "install --trust-policy=MediumSecurity"
expect(out).to include("security policy didn't allow")
end
it "will succeed with no policy" do
bundle "install"
expect(exitstatus).to eq(0) if exitstatus
end
end
describe "policies with signed gems and no CA" do
before do
build_security_repo
gemfile <<-G
source "file://#{security_repo}"
gem "signed_gem"
G
end
it "will fail with High Security setting, gem is self-signed" do
bundle "install --trust-policy=HighSecurity"
expect(out).to include("security policy didn't allow")
end
it "will fail with Medium Security setting, gem is self-signed" do
bundle "install --trust-policy=MediumSecurity"
expect(out).to include("security policy didn't allow")
end
it "will succeed with Low Security setting, low security accepts self signed gem" do
bundle "install --trust-policy=LowSecurity"
expect(exitstatus).to eq(0) if exitstatus
should_be_installed "signed_gem 1.0"
end
it "will succeed with no policy" do
bundle "install"
expect(exitstatus).to eq(0) if exitstatus
should_be_installed "signed_gem 1.0"
end
end
| 30.705128 | 120 | 0.709395 |
87c74f25060e31c43e2c1ab3f3e38e3bc27ea9e6 | 298 | desc "run JavaScriptLint on the source"
task :lint do
check 'eslint', 'JavaScript Lint', 'npm install eslint --global'
Dir.glob(File.join(File.expand_path("../../", __FILE__), 'lib', '**', '*.js')).each do |file|
print '%-75s ' % file
system("eslint -c .eslintrc #{file}")
end
end
| 29.8 | 95 | 0.620805 |
33f7129ab0a30051bd7892ec41f9cf4a7eaa3c99 | 283 | require 'securerandom'
module Amnesie
class Host
def initialize
@nb = rand(8..25)
@hostname = SecureRandom.alphanumeric(@ng)
Nito::Hostname.new(@hostname)
puts to_s
end
def to_s
"Your hostname will become #{@hostname}"
end
end
end
| 16.647059 | 48 | 0.625442 |
d580c49386050fa052105048862636c0e60dc2e7 | 637 | require 'spec_helper'
describe 'loader::load' do
let(:pre_condition) {[
'class my_class1() {}',
'class my_class2() {}',
'class my_class3() {}',
]}
let(:params) {{
:classes => {
'my_class1' => false,
'my_class2' => true,
}
}}
context 'exclude' do
let(:title) { 'my_class1' }
it { should_not contain_class('my_class1') }
end
context 'include' do
let(:title) { 'my_class2' }
it { should contain_class('my_class2') }
end
context 'undefined' do
let(:title) { 'my_class3' }
it { should_not contain_class('my_class2') }
end
end
# vim: set expandtab sw=2 ts=2:
| 17.694444 | 48 | 0.582418 |
38b13de992127c09cd2f831acb3c4a2f735ec718 | 260 | require 'open3'
module Clipboard
module Mac
extend self
def paste(_ = nil)
`pbpaste`
end
def copy(data)
Open3.popen3( 'pbcopy' ){ |input, _, _| input << data }
paste
end
def clear
copy ''
end
end
end
| 12.380952 | 61 | 0.542308 |
62c70885ff0a4b568f5367764bb7d91c10e317be | 426 | class GuessLetterValidator < ActiveModel::Validator
ERROR_STRING = {
must_be_single_upper_alpha: "must be a single uppercase letter",
}
def validate(record)
must_be_single_upper_alpha(record)
end
private
def must_be_single_upper_alpha(record)
if record.letter.nil? || record.letter.match(/\A[A-Z]\z/).nil?
record.errors.add :letter, ERROR_STRING[:must_be_single_upper_alpha]
end
end
end
| 23.666667 | 74 | 0.737089 |
5d2365bf7a6ca7d9e12f2e1f0ee3ae9f22ca86b7 | 4,833 | require 'docker'
require 'httparty'
class CoinContainer
def create(options = {})
default_options = {
image: "stronghands/base",
shutdown_at_exit: true,
delete_at_exit: false,
remove_addr_after_shutdown: true,
remove_wallet_after_shutdown: false,
}
options = default_options.merge(options)
links = options[:links]
case links
when Hash
links = links.map { |link_name, alias_name| [link_name, alias_name] }
when Array
links = links.map do |n|
name = case n
when String then n
when CoinContainer then n.name
else raise "Unknown link: #{n.inspect}"
end
[name, name.sub(/^\//, '')]
end
when nil
links = []
else
raise "Invalid links"
end
name = options[:name]
connect_cmd = (options[:link_with_connect] ? "-connect" : "-addnode")
connects = links.map do |linked_name, alias_name|
upname = alias_name.upcase
"#{connect_cmd}=$#{upname}_PORT_6903_TCP_ADDR:$#{upname}_PORT_6903_TCP_PORT"
end
default_args = {
testnet: true,
printtoconsole: true,
rpcuser: 'bob',
rpcpassword: 'bar',
rpcallowip: '*.*.*.*',
logtimestamps: true,
keypool: 1,
stakegen: false,
dnsseed: false,
}
args = default_args.merge(options[:args] || {})
cmd_args = args.map do |key, value|
case value
when true
"-#{key}"
when false
"-#{key}=0"
when Numeric
"-#{key}=#{value}"
else
"-#{key}=\"#{value}\""
end
end
cmd_args += connects
bash_cmd = ""
if options[:show_environment]
bash_cmd += "echo Environment:; env; "
end
bash_cmd += "./stronghandsd " + cmd_args.join(" ")
if options[:remove_addr_after_shutdown]
bash_cmd += "; rm -f /root/.stronghands/testnet/peers.dat"
end
if options[:remove_wallet_after_shutdown]
bash_cmd += "; rm /root/.stronghands/testnet/wallet.dat"
end
command = [
"stdbuf", "-oL", "-eL",
'/bin/bash', '-c',
bash_cmd,
]
create_options = {
'Image' => options[:image],
'WorkingDir' => '/code',
'Tty' => true,
'Cmd' => command,
'ExposedPorts' => {
"6903/tcp" => {},
"6904/tcp" => {},
},
'name' => name,
}
node_container = Docker::Container.create(create_options)
if options[:shutdown_at_exit]
at_exit do
shutdown rescue nil
end
end
if options[:delete_at_exit]
at_exit do
container.delete(force: true)
end
end
node_container.start(
'Binds' => ["#{File.expand_path('../../..', __FILE__)}:/code"],
'PortBindings' => {
"6904/tcp" => [{}],
"6903/tcp" => [{}],
},
'Links' => links.map { |link_name, alias_name| "#{link_name}:#{alias_name}" },
)
@container = node_container
end
def load_data
@json = @container.json
@name = @json["Name"]
ports = @json["NetworkSettings"]["Ports"]
if ports.nil?
raise "Unable to get port. Usualy this means the daemon process failed to start."
end
port = ports["6904/tcp"].first["HostPort"].to_i
@rpc_port = port
@port= ports["6903/tcp"].first["HostPort"].to_i
end
def initialize(options = {})
if id = options[:id]
get(id)
else
create(options)
end
load_data
end
def get(id)
@container = Docker::Container.get(id)
end
attr_reader :rpc_port, :port, :container, :name
def json
container.json
end
def id
@json["Id"]
end
def rpc(method, *params)
data = {
method: method,
params: params,
id: 'jsonrpc',
}
url = "http://localhost:#{rpc_port}/"
auth = {
username: "bob",
password: "bar",
}
response = HTTParty.post url, body: data.to_json, headers: { 'Content-Type' => 'application/json' }, basic_auth: auth
result = JSON.parse(response.body)
raise result.inspect if result["error"]
result["result"]
end
def wait_for_boot
begin
rpc("getinfo")
rescue Errno::ECONNREFUSED, Errno::ECONNRESET, EOFError, Errno::EPIPE
sleep 0.1
retry
end
end
def commit(repo)
image = container.commit
image.tag 'repo' => repo
end
def shutdown
rpc("shutdown")
end
def wait_for_shutdown
container.wait
end
def block_count
rpc("getblockcount").to_i
end
def generate_stake(parent = nil)
rpc("generatestake", *[parent].compact)
end
def top_hash
rpc("getblockhash", rpc("getblockcount"))
end
def connection_count
rpc("getconnectioncount").to_i
end
def info
rpc "getinfo"
end
def new_address(account = "")
rpc "getnewaddress", account
end
end
| 21.104803 | 121 | 0.576247 |
e2b587fee261e25a6fbe0cef659215db90c24f44 | 5,517 | class Cuboid
# Only allow observer to see vertices, as the other
# dimensions are found with arithmetic. It is important to only supply
# the user with the information they need.
attr_reader :vertices
# instantiates a cuboid with its origin and its dimensions
# origin = [length, height, width]
# length ~ x
# height ~ y
# width ~ z
def initialize(origin = [rand(10) - 5, rand(10) - 5, rand(10) - 5], length, width, height)
if length <= 0 || height <= 0 || width <= 0
raise ArgumentError, 'length, width, and height must be nonzero, positive number'
end
@origin = origin
@l = length
@h = height
@w = width
end
# Reassigns origin of cuboid. Returns new origin.
def move_to!(x, y, z)
@origin = [x, y, z]
end
# calculates and returns an array of the eight vertices
# Each vertex is given as (x, y, z)
def vertices
vertices = []
vertices << [(@origin[0] + @l/2.0), (@origin[1] + @h/2.0), (@origin[2] + @w/2.0)]
vertices << [(@origin[0] + @l/2.0), (@origin[1] + @h/2.0), (@origin[2] - @w/2.0)]
vertices << [(@origin[0] + @l/2.0), (@origin[1] - @h/2.0), (@origin[2] - @w/2.0)]
vertices << [(@origin[0] + @l/2.0), (@origin[1] - @h/2.0), (@origin[2] + @w/2.0)]
vertices << [(@origin[0] - @l/2.0), (@origin[1] - @h/2.0), (@origin[2] + @w/2.0)]
vertices << [(@origin[0] - @l/2.0), (@origin[1] - @h/2.0), (@origin[2] - @w/2.0)]
vertices << [(@origin[0] - @l/2.0), (@origin[1] + @h/2.0), (@origin[2] - @w/2.0)]
vertices << [(@origin[0] - @l/2.0), (@origin[1] + @h/2.0), (@origin[2] + @w/2.0)]
vertices
end
# Returns true if the two cuboids intersect each other.
# False otherwise. If one cuboid is within another, that counts as
# an intersection.
# This checks each dimension to ensure that there is at least one
# point that overlaps in the (x, y, z) plane.
def intersects?(other)
self_index = dimensions(self.vertices)
other_index = dimensions(other.vertices)
intersection = {}
intersection[:x] = self_index[:x] & other_index[:x]
intersection[:y] = self_index[:y] & other_index[:y]
intersection[:z] = self_index[:z] & other_index[:z]
intersection.value?([]) ? false : true
end
# This method will rotate the cuboid. If the cuboid's rotation
# is impeded, the rotation will not happenand the function will return
# false. If the rotation occurs, the new vertices will be returned.
# The rotation will be at 90 degree intervals.
# Walls will be input as an array of other Cuboid objects.
# The manner that this method checks for impediments is a good
# approximation, but is not entirely accurate. This method simply
# expands the cuboid about the axis it is being rotated by its scalar
# distance from origin to appropriate vertex. It then checks to see if
# there are now any intersections at this larger size. If not, then
# the box will be able to rotate smoothly.
# In order to correct this approximation, I could convert the coords
# of the box into spherical coordinates and call #intersection? at
# each deg of rotation.
def rotate(axis = :x, walls = [])
# check to see if there are already impedements
walls.each do |wall|
return false if self.intersects?(wall)
end
case axis
when :x
if !walls.empty?
dist = Math.sqrt((@h/2) ** 2 + (@w/2) ** 2)
temp = Cuboid.new(@origin, @l, dist, dist)
walls.each do |wall|
return false if temp.intersects?(wall)
end
end
rotate_x
when :y
if !walls.empty?
dist = Math.sqrt((@l/2) ** 2 + (@w/2) ** 2)
temp = Cuboid.new(@origin, dist, @h, dist)
walls.each do |wall|
return false if temp.intersects?(wall)
end
end
rotate_y
when :z
if !walls.empty?
dist = Math.sqrt((@h/2) ** 2 + (@l/2) ** 2)
temp = Cuboid.new(@origin, dist, dist, @w)
walls.each do |wall|
return false if temp.intersects?(wall)
end
end
rotate_z
else
raise ArgumentError, "Please use a symbol to identify the axis: :x, :y, or :z"
end
self.vertices
end
private
# Outputs incremented ranges for length, height, and width of a cuboid.
# This will be used in calculation to determine if cuboids intersect.
# The incrementor used is .01 so as to ensure accuracy, but not
# decreases the speed of the program. For greater accuracy, the
# incrementor would be smaller. For greater speed, the incrementor
# would be larger
def dimensions(vertices)
dims = { x: [], y: [], z: [] }
# length or x-axis
if vertices[0][0] < vertices[-1][0]
(vertices[0][0]..vertices[-1][0]).step(0.01) { |n| dims[:x] << n }
else
(vertices[-1][0]..vertices[0][0]).step(0.01) { |n| dims[:x] << n }
end
# height or y-axis
if vertices[0][1] < vertices[3][1]
(vertices[0][1]..vertices[3][1]).step(0.01) { |n| dims[:y] << n }
else
(vertices[3][1]..vertices[0][1]).step(0.01) { |n| dims[:y] << n }
end
# width or z-axis
if vertices[0][2] < vertices[1][2]
(vertices[0][2]..vertices[1][2]).step(0.01) { |n| dims[:z] << n }
else
(vertices[1][2]..vertices[0][2]).step(0.01) { |n| dims[:z] << n }
end
dims
end
# helper methods to reassign vertices upon successful rotation
def rotate_x
@w, @h = @h, @w
end
def rotate_y
@w, @l = @l, @w
end
def rotate_z
@l, @w = @w, @l
end
end
| 30.821229 | 92 | 0.598876 |
6ae5a97b3b431d7f8597a5674a1565125397d596 | 1,206 | object @order
extends 'spree/api/v1/orders/order'
if lookup_context.find_all("spree/api/v1/orders/#{root_object.state}").present?
extends "spree/api/v1/orders/#{root_object.state}"
end
child billing_address: :bill_address do
extends 'spree/api/v1/addresses/show'
end
child shipping_address: :ship_address do
extends 'spree/api/v1/addresses/show'
end
child line_items: :line_items do
extends 'spree/api/v1/line_items/show'
end
child payments: :payments do
attributes *payment_attributes
child payment_method: :payment_method do
attributes :id, :name
end
child source: :source do
if @current_user_roles.include?('admin')
attributes *payment_source_attributes + [:gateway_customer_profile_id, :gateway_payment_profile_id]
else
attributes *payment_source_attributes
end
end
end
child shipments: :shipments do
extends 'spree/api/v1/shipments/small'
end
child adjustments: :adjustments do
extends 'spree/api/v1/adjustments/show'
end
# Necessary for backend's order interface
node :permissions do
{ can_update: current_ability.can?(:update, root_object) }
end
child valid_credit_cards: :credit_cards do
extends 'spree/api/v1/credit_cards/show'
end
| 23.192308 | 105 | 0.768657 |
217aa185767969749fa384535fb9656046490dc7 | 2,100 | # frozen_string_literal: true
require 'spec_helper'
require_relative '../../../metrics_server/metrics_server'
# End-to-end tests for the metrics server process we use to serve metrics
# from forking applications (Sidekiq, Puma) to the Prometheus scraper.
RSpec.describe 'bin/metrics-server', :aggregate_failures do
let(:config_file) { Tempfile.new('gitlab.yml') }
let(:config) do
{
'test' => {
'monitoring' => {
'web_exporter' => {
'address' => 'localhost',
'enabled' => true,
'port' => 3807
},
'sidekiq_exporter' => {
'address' => 'localhost',
'enabled' => true,
'port' => 3807
}
}
}
}
end
%w(puma sidekiq).each do |target|
context "with a running server targeting #{target}" do
let(:metrics_dir) { Dir.mktmpdir }
before do
# We need to send a request to localhost
WebMock.allow_net_connect!
config_file.write(YAML.dump(config))
config_file.close
@pid = MetricsServer.spawn(target, metrics_dir: metrics_dir, gitlab_config: config_file.path, wipe_metrics_dir: true)
end
after do
webmock_enable!
if @pid
pgrp = Process.getpgid(@pid)
Timeout.timeout(10) do
Process.kill('TERM', -pgrp)
Process.waitpid(@pid)
end
expect(Gitlab::ProcessManagement.process_alive?(@pid)).to be(false)
end
rescue Errno::ESRCH => _
# 'No such process' means the process died before
ensure
config_file.unlink
FileUtils.rm_rf(metrics_dir, secure: true)
end
it 'serves /metrics endpoint' do
expect do
Timeout.timeout(10) do
http_ok = false
until http_ok
sleep 1
response = Gitlab::HTTP.try_get("http://localhost:3807/metrics", allow_local_requests: true)
http_ok = response&.success?
end
end
end.not_to raise_error
end
end
end
end
| 26.582278 | 125 | 0.571905 |
1dd4cbbb5419261135934a6dcd52989e4b03819e | 1,468 | require 'rails_helper'
include AuthHelper
describe QuestionsController do
describe 'POST create' do
let(:question_params) {
{ title: "foo", answer_type: "string" }
}
context "not logged in" do
before { post 'create', params: { question: question_params } }
it { should redirect_to new_session_path }
end
context "logged in" do
let!(:user) { manager_basic_login }
context "valid params" do
before { post 'create', params: { question: question_params } }
it { expect(Question.count).to eq(1) }
it { should redirect_to edit_organization_path(user.organization) }
end
context "invalid params" do
before { post 'create', params: { question: {title: nil} } }
it { expect(Question.count).to eq(0) }
it { should redirect_to edit_organization_path(user.organization) }
end
end
end
describe "DELETE destroy" do
let(:question) { FactoryBot.create(:question) }
context "not logged in" do
before { delete 'destroy', params: { id: question.to_param } }
it { should redirect_to new_session_path }
end
context "logged in" do
let!(:user) { manager_basic_login }
context "valid params" do
before { delete 'destroy', params: { id: question.to_param } }
it { expect(Question.count).to eq(0) }
it { should redirect_to edit_organization_path(user.organization) }
end
end
end
end
| 28.784314 | 75 | 0.638283 |
1c053d3b700c60b24c6c15a3ccfdf3bc5283e1e7 | 1,191 | cask "synology-cloud-station-backup" do
version "4.3.3,4469"
sha256 "1759be61a09cacd976969f71b0c0f12f34684976de6ad98323c512aec8f3399d"
url "https://global.download.synology.com/download/Tools/CloudStationBackup/#{version.before_comma}-#{version.after_comma}/Mac/Installer/synology-cloud-station-backup-#{version.after_comma}.dmg"
name "Synology Cloud Station Backup"
desc "Back up files to a centralized Synology NAS"
homepage "https://www.synology.com/"
livecheck do
url "https://www.synology.com/en-us/releaseNote/CloudStationBackup"
strategy :page_match do |page|
match = page.match(/Version:\s*(\d+(?:\.\d+)+)-(\d+)/i)
next if match.blank?
"#{match[1]},#{match[2]}"
end
end
auto_updates true
pkg "Install Cloud Station Backup.pkg"
uninstall quit: [
"com.synology.CloudStationBackup",
"com.synology.CloudStationBackupUI",
],
pkgutil: [
"com.synology.CloudStationBackup",
"com.synology.CloudStationBackupUI",
],
launchctl: "com.synology.Synology Cloud Station Backup"
zap trash: "~/Library/Preferences/com.synology.CloudStationBackupUI.plist"
end
| 33.083333 | 196 | 0.689337 |
e80285869911f2de6b584da07bebede9086d480f | 456 | module VCAP::CloudController
module Jobs
module Runtime
class BlobstoreUpload < Struct.new(:local_path, :blobstore_key, :blobstore_name)
def perform
begin
blobstore = CloudController::DependencyLocator.instance.public_send(blobstore_name)
blobstore.cp_to_blobstore(local_path, blobstore_key)
ensure
FileUtils.rm_f(local_path)
end
end
end
end
end
end
| 26.823529 | 95 | 0.651316 |
1c918580a65a21c29237343067c0d3fd88150398 | 1,969 | ##
# Copyright 2017-2018 Bryan T. Meyers
#
# 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 'test/unit'
require_relative('../../../lib/wiki-that')
class RuleGenTest < Test::Unit::TestCase
def test_empty
gen = WikiThat::HTMLGenerator.new('', 'wiki', 'BOB', 'sub/folder', 'media/folder')
gen.generate
assert_true(gen.success?, 'Generation should have succeeded')
assert_equal('', gen.result)
end
def test_incomplete1
start = '-'
gen = WikiThat::HTMLGenerator.new(start, 'wiki', 'BOB', 'sub/folder', 'media/folder')
gen.generate
assert_true(gen.success?, 'Generation should have succeeded')
assert_equal('<p>-</p>', gen.result)
end
def test_incomplete2
start = '--'
gen = WikiThat::HTMLGenerator.new(start, 'wiki', 'BOB', 'sub/folder', 'media/folder')
gen.generate
assert_true(gen.success?, 'Generation should have succeeded')
assert_equal('—', gen.result)
end
def test_complete1
start = '---'
gen = WikiThat::HTMLGenerator.new(start, 'wiki', 'BOB', 'sub/folder', 'media/folder')
gen.generate
assert_true(gen.success?, 'Generation should have succeeded')
assert_equal('<hr />', gen.result)
end
def test_complete2
start = '----'
gen = WikiThat::HTMLGenerator.new(start, 'wiki', 'BOB', 'sub/folder', 'media/folder')
gen.generate
assert_true(gen.success?, 'Generation should have succeeded')
assert_equal('<hr />', gen.result)
end
end
| 33.372881 | 91 | 0.687151 |
e245a095fa7d75f9c4dc9dc3002b9d77159090b6 | 1,805 | class ApplicationController < ActionController::Base
before_filter :authenticate_user!
protect_from_forgery
## CanCan permisisons
## https://github.com/ryanb/cancan
##Automatically does the following:
##@product = Product.find(params[:id])
##authorize! :discontinue, @product
## ----------------------------------
#check_authorization :unless => :devise_controller?
#load_and_authorize_resource :unless => :devise_controller?
rescue_from CanCan::AccessDenied do |exception|
##redirect_to root_url, :alert => exception.message
render :json => Api::SessionsController.forbidden_info(current_user).to_json, :status => :forbidden
end
# end CanCan permissions
# userstamp
include Userstamp
# from http://stackoverflow.com/a/94626
def render_csv(filename = nil)
require 'csv'
filename ||= params[:action]
filename += '.csv'
if request.env['HTTP_USER_AGENT'] =~ /msie/i
headers['Pragma'] = 'public'
headers["Content-type"] = "text/plain"
headers['Cache-Control'] = 'no-cache, must-revalidate, post-check=0, pre-check=0'
headers['Content-Disposition'] = "attachment; filename=\"#{filename}\""
headers['Expires'] = "0"
else
headers["Content-Type"] ||= 'text/csv'
headers["Content-Disposition"] = "attachment; filename=\"#{filename}\""
end
render :layout => false
end
def add_archived_at_header(model)
if model.respond_to?(:deleted_at) && !model.deleted_at.blank?
response.headers["X-Archived-At"] = model.deleted_at
end
end
def no_content_as_json
head :no_content, :content_type => "application/json"
end
private
#def set_stamper
# User.stamper = current_user if user_signed_in?
#end
def set_stampers
User.stamper = self.current_user
end
end
| 27.348485 | 103 | 0.6759 |
330ddbc3333951f4250cf7a5e18d736a7dd742f9 | 4,985 | # Copyright (c) 2016, 2022, Oracle and/or its affiliates. All rights reserved.
# This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may choose either license.
require 'date'
require_relative 'enable_database_insight_details'
# rubocop:disable Lint/UnneededCopDisableDirective, Metrics/LineLength
module OCI
# The information about database to be analyzed.
class Opsi::Models::EnableEmManagedExternalDatabaseInsightDetails < Opsi::Models::EnableDatabaseInsightDetails
# Attribute mapping from ruby-style variable name to JSON key.
def self.attribute_map
{
# rubocop:disable Style/SymbolLiteral
'entity_source': :'entitySource'
# rubocop:enable Style/SymbolLiteral
}
end
# Attribute type mapping.
def self.swagger_types
{
# rubocop:disable Style/SymbolLiteral
'entity_source': :'String'
# rubocop:enable Style/SymbolLiteral
}
end
# rubocop:disable Metrics/CyclomaticComplexity, Metrics/AbcSize, Metrics/PerceivedComplexity
# rubocop:disable Metrics/MethodLength, Layout/EmptyLines, Style/SymbolLiteral
# Initializes the object
# @param [Hash] attributes Model attributes in the form of hash
def initialize(attributes = {})
return unless attributes.is_a?(Hash)
attributes['entitySource'] = 'EM_MANAGED_EXTERNAL_DATABASE'
super(attributes)
end
# rubocop:enable Metrics/CyclomaticComplexity, Metrics/AbcSize, Metrics/PerceivedComplexity
# rubocop:enable Metrics/MethodLength, Layout/EmptyLines, Style/SymbolLiteral
# rubocop:disable Metrics/CyclomaticComplexity, Metrics/AbcSize, Metrics/PerceivedComplexity, Layout/EmptyLines
# Checks equality by comparing each attribute.
# @param [Object] other the other object to be compared
def ==(other)
return true if equal?(other)
self.class == other.class &&
entity_source == other.entity_source
end
# rubocop:enable Metrics/CyclomaticComplexity, Metrics/AbcSize, Metrics/PerceivedComplexity, Layout/EmptyLines
# @see the `==` method
# @param [Object] other the other object to be compared
def eql?(other)
self == other
end
# rubocop:disable Metrics/AbcSize, Layout/EmptyLines
# Calculates hash code according to all attributes.
# @return [Fixnum] Hash code
def hash
[entity_source].hash
end
# rubocop:enable Metrics/AbcSize, Layout/EmptyLines
# rubocop:disable Metrics/AbcSize, Layout/EmptyLines
# Builds the object from hash
# @param [Hash] attributes Model attributes in the form of hash
# @return [Object] Returns the model itself
def build_from_hash(attributes)
return nil unless attributes.is_a?(Hash)
self.class.swagger_types.each_pair do |key, type|
if type =~ /^Array<(.*)>/i
# check to ensure the input is an array given that the the attribute
# is documented as an array but the input is not
if attributes[self.class.attribute_map[key]].is_a?(Array)
public_method("#{key}=").call(
attributes[self.class.attribute_map[key]]
.map { |v| OCI::Internal::Util.convert_to_type(Regexp.last_match(1), v) }
)
end
elsif !attributes[self.class.attribute_map[key]].nil?
public_method("#{key}=").call(
OCI::Internal::Util.convert_to_type(type, attributes[self.class.attribute_map[key]])
)
end
# or else data not found in attributes(hash), not an issue as the data can be optional
end
self
end
# rubocop:enable Metrics/AbcSize, Layout/EmptyLines
# Returns the string representation of the object
# @return [String] String presentation of the object
def to_s
to_hash.to_s
end
# Returns the object in the form of hash
# @return [Hash] Returns the object in the form of hash
def to_hash
hash = {}
self.class.attribute_map.each_pair do |attr, param|
value = public_method(attr).call
next if value.nil? && !instance_variable_defined?("@#{attr}")
hash[param] = _to_hash(value)
end
hash
end
private
# Outputs non-array value in the form of hash
# For object, use to_hash. Otherwise, just return the value
# @param [Object] value Any valid value
# @return [Hash] Returns the value in the form of hash
def _to_hash(value)
if value.is_a?(Array)
value.compact.map { |v| _to_hash(v) }
elsif value.is_a?(Hash)
{}.tap do |hash|
value.each { |k, v| hash[k] = _to_hash(v) }
end
elsif value.respond_to? :to_hash
value.to_hash
else
value
end
end
end
end
# rubocop:enable Lint/UnneededCopDisableDirective, Metrics/LineLength
| 34.143836 | 245 | 0.678034 |
1d29627c6470ca755532e79b79362f88c3fcd145 | 3,065 | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe(Take2::Configuration) do
describe 'default configurations' do
let(:default) { described_class.new }
it 'has correct default value for retries' do
expect(default.retries).to(eql(3))
end
it 'has correct default retriable errors array' do
expect(default.retriable).to(eql([]))
end
it 'has default proc for retry_proc' do
p = proc {}
expect(default.retry_proc.call).to(eql(p.call))
end
it 'has default proc for retry_condition_proc' do
p = proc { false }
expect(default.retry_condition_proc.call).to(eql(p.call))
end
it 'has correct default value for backoff_intervals' do
expect(default.backoff_intervals).to eql Array.new(10, 3)
end
end
describe 'overwriting the default configurations' do
context 'with valid hash' do
let!(:new_configs_hash) do
{
retries: 2,
retriable: [Net::HTTPRetriableError],
retry_condition_proc: proc { true },
retry_proc: proc { 2 * 2 },
backoff_intervals: [1, 2, 3, 4, 5]
}
end
let!(:new_configuration) { described_class.new(new_configs_hash).to_hash }
[:retries, :retriable, :retry_proc, :retry_condition_proc, :backoff_intervals].each do |key|
it "sets the #{key} key" do
if new_configs_hash[key].respond_to?(:call)
expect(new_configuration[key].call).to(eql(new_configs_hash[key].call))
else
expect(new_configuration[key]).to(eql(new_configs_hash[key]))
end
end
end
end
context 'with invalid hash' do
context 'when retries set to invalid value' do
it 'raises ArgumentError' do
expect { described_class.new(retries: -1) }.to(raise_error(ArgumentError))
expect { described_class.new(retries: 0) }.to(raise_error(ArgumentError))
end
end
context 'when retriable set to invalid value' do
it 'raises ArgumentError' do
expect { described_class.new(retriable: StandardError) }.to(raise_error(ArgumentError))
end
end
context 'when retry_proc set to invalid value' do
it 'raises ArgumentError' do
expect { described_class.new(retry_proc: {}) }.to(raise_error(ArgumentError))
end
end
context 'when retry_condition_proc set to invalid value' do
it 'raises ArgumentError' do
expect { described_class.new(retry_condition_proc: {}) }.to(raise_error(ArgumentError))
end
end
context 'when backoff_intervals has incorrect type' do
it 'raises ArgumentError' do
expect { described_class.new(backoff_intervals: 1) }.to(raise_error(ArgumentError))
end
end
context 'when backoff_intervals size smaller then number of retries' do
it 'raises ArgumentError' do
expect { described_class.new(backoff_intervals: [1]) }.to(raise_error(ArgumentError))
end
end
end
end
end
| 31.597938 | 98 | 0.646982 |
081a94ab359ecc048efc3f1b388dd5b6fbea3350 | 1,039 | # coding: utf-8
$:.push File.expand_path("../lib", __FILE__)
# Maintain your gem's version:
require "herstory/version"
# Describe your gem and declare its dependencies:
Gem::Specification.new do |s|
s.name = "herstory"
s.version = Herstory::VERSION
s.authors = ["Joachim Garth"]
s.email = ["[email protected]"]
s.homepage = "https://github.com/crispymtn/herstory"
s.summary = "Tracks changes to your AR models and their associations."
s.description = "Tracks changes to your AR models and their associations, even works with has_many :through."
s.license = "MIT"
s.files = Dir["{app,config,db,lib}/**/*", "MIT-LICENSE", "Rakefile", "README.rdoc"]
s.add_dependency "rails", "~> 4.2.0"
s.add_development_dependency "rspec"
s.add_development_dependency "guard-rspec"
s.add_development_dependency "pry-rails"
s.add_development_dependency "pry-byebug"
s.add_development_dependency "rspec-rails"
s.add_development_dependency "sqlite3"
s.add_development_dependency "guard"
end
| 35.827586 | 111 | 0.708373 |
aba630e87c82861f2702d130a6ac14ad34f38a3c | 2,707 | module Telegram
# Telegram-CLI Connection
#
# @note Don't make a connection directly to the telegram-cli
# @see Client
# @see ConnectionPool
# @version 0.1.0
class Connection < EM::Connection
# Initialize connection
#
# @version 0.1.0
def initialize
super
@connected = false
@on_connect = nil
@on_disconnect = nil
@callback = nil
@available = true
@data = ''
end
# @return [Bool] the availiability of current connection
def available?
@available
end
# Communicate telegram-rb with telegram-cli connection
#
# @param [Array<String>] messages Messages that will be sent
# @yieldparam [Block] callback Callback block that will be called when finished
def communicate(*messages, &callback)
@available = false
@data = ''
@callback = callback
messages = messages.first if messages.size == 1 and messages.first.is_a?(Array)
messages = messages.join(' ') << "\n"
send_data(messages)
end
# Set a block that will be called when connected
#
# @param [Block] block
def on_connect=(block)
@on_connect = block
end
# Set a block that will be called when disconnected
#
# @param [Block] block
def on_disconnect=(block)
@on_disconnect = block
end
# This method will be called by EventMachine when connection completed
#
# @api private
def connection_completed
@connected = true
@on_connect.call unless @on_connect.nil?
end
# This method will be called by EventMachine when connection unbinded
#
# @api private
def unbind
@connected = false
@on_disconnect.call unless @on_disconnect.nil?
end
# @return [Bool] the availiability of current connection
def connected?
@connected
end
# This method will be called by EventMachine when data arrived
# then parse given data and execute callback method if exists
#
# @api private
def receive_data(data)
@data << data
return unless data.index("\n\n")
begin
result = _receive_data(@data)
rescue
raise
result = nil
end
@callback.call(!result.nil?, result) unless @callback.nil?
@callback = nil
@available = true
end
protected
# Parse received data to correct json format and then convert to Ruby {Hash}
#
# @api private
def _receive_data(data)
if data[0..6] == 'ANSWER '
lf = data.index("\n") + 1
lflf = data.index("\n\n", lf) - 1
data = data[lf..lflf]
data = Oj.load(data, :mode => :compat)
end
data
end
end
end
| 24.609091 | 85 | 0.61655 |
ed45e77e8b8e32d6230acbd7bfc14e3a894319c1 | 982 | require 'spec_helper'
describe 'example' do
on_supported_os.each do |os, facts|
context "on #{os}" do
let(:facts) { facts }
context 'with defaults for all parameters' do
it { is_expected.to contain_class('example') }
it { is_expected.to contain_anchor('example::begin').that_comes_before('Class[example::Install]') }
it { is_expected.to contain_class('example::install').that_comes_before('Class[example::Config]') }
it { is_expected.to contain_class('example::config').that_notifies('Class[example::Service]') }
it { is_expected.to contain_class('example::service').that_comes_before('Anchor[example::end]') }
it { is_expected.to contain_anchor('example::end') }
it { is_expected.to contain_group('example') }
it { is_expected.to contain_package('example') }
it { is_expected.to contain_service('example') }
it { is_expected.to contain_user('example') }
end
end
end
end
| 44.636364 | 107 | 0.669043 |
28fc1fb21475acf23e87a40718a7a29dac48d22d | 1,470 | # Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
module Azure::OperationalInsights::Mgmt::V2020_03_01_preview
module Models
#
# The core summary of a search.
#
class CoreSummary
include MsRestAzure
# @return [String] The status of a core summary.
attr_accessor :status
# @return [Integer] The number of documents of a core summary.
attr_accessor :number_of_documents
#
# Mapper for CoreSummary class as Ruby Hash.
# This will be used for serialization/deserialization.
#
def self.mapper()
{
client_side_validation: true,
required: false,
serialized_name: 'CoreSummary',
type: {
name: 'Composite',
class_name: 'CoreSummary',
model_properties: {
status: {
client_side_validation: true,
required: false,
serialized_name: 'status',
type: {
name: 'String'
}
},
number_of_documents: {
client_side_validation: true,
required: true,
serialized_name: 'numberOfDocuments',
type: {
name: 'Number'
}
}
}
}
}
end
end
end
end
| 25.789474 | 70 | 0.527211 |
0317cc4edb0adb20b8420dfd826f9f15f6b238a0 | 3,198 | require 'travis/cli'
require 'travis/tools/github'
require 'json'
module Travis
module CLI
class Login < ApiCommand
skip :authenticate
description "authenticates against the API and stores the token"
on('-g', '--github-token TOKEN', 'identify by GitHub token')
on('-T', '--auto-token', 'try to figure out who you are automatically (might send another apps token to Travis, token will not be stored)')
on('-p', '--auto-password', 'try to load password from OSX keychain (will not be stored)')
on('-a', '--auto', 'shorthand for --auto-token --auto-password') { |c| c.auto_token = c.auto_password = true }
on('-u', '--user LOGIN', 'user to log in as') { |c,n| c.user_login = n }
on('-M', '--no-manual', 'do not use interactive login')
on('--list-github-token', 'instead of actually logging in, list found GitHub tokens')
on('--skip-token-check', 'don\'t verify the token with github')
attr_accessor :user_login
def list_token
github.after_tokens = proc { }
github.each_token do |token|
say token
end
end
def login
session.access_token = nil
github.with_token do |token|
endpoint_config['access_token'] = github_auth(token)
error("user mismatch: logged in as %p instead of %p" % [user.login, user_login]) if user_login and user.login != user_login
success("Successfully logged in as #{user.login}!")
end
end
def run
list_github_token ? list_token : login
end
def github
@github ||= begin
load_gh
Tools::Github.new(session.config['github']) do |g|
g.note = "temporary token to identify with the travis command line client against #{api_endpoint}"
g.manual_login = no_manual.nil?
g.explode = explode?
g.github_token = github_token
g.auto_token = auto_token
g.auto_password = auto_password
g.github_login = user_login
g.check_token = !skip_token_check?
g.drop_token = true
g.ask_login = proc { ask("Username: ") }
g.ask_password = proc { |user| ask("Password for #{user}: ") { |q| q.echo = "*" } }
g.ask_otp = proc { |user| ask("Two-factor authentication code for #{user}: ") }
g.login_header = proc { login_header }
g.debug = proc { |log| debug(log) }
g.after_tokens = proc { g.explode = true and error("no suitable github token found") }
end
end
end
def login_header
say "We need your #{color("GitHub login", :important)} to identify you."
say "This information will #{color("not be sent to Travis CI", :important)}, only to #{color(github_endpoint.host, :info)}."
say "The password will not be displayed."
empty_line
say "Try running with #{color("--github-token", :info)} or #{color("--auto", :info)} if you don't want to enter your password anyways."
empty_line
end
end
end
end
| 42.078947 | 153 | 0.581301 |
28e60c3d1d569f5035f7d6e1d112124ccad62300 | 540 | module AlephExecutables
class SetupDemo
HOST = 'aleph-public.cdiwpivlvfxt.us-east-1.rds.amazonaws.com'.freeze
DB = 'aleph_public'.freeze
PORT = '5432'.freeze
USER = 'read_only'.freeze
PASSWORD = '@lephR3@d0nlee'.freeze
def initialize(options)
@options = options
end
def execute!
options = @options.select{ |k,v| k == :config_path}.merge(seed_db: true)
Playground.setup(HOST, DB, PORT, USER, PASSWORD, options)
end
end
end
| 28.421053 | 85 | 0.592593 |
6a0ed3b990f2c0cd0c4ab5549356bdf9fbefdb6d | 2,173 | # Copyright 2018 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.
# [START apps_script_api_execute]
SCRIPT_ID = "ENTER_YOUR_SCRIPT_ID_HERE".freeze
# Create an execution request object.
request = Google::Apis::ScriptV1::ExecutionRequest.new(
function: "getFoldersUnderRoot"
)
begin
# Make the API request.
resp = service.run_script SCRIPT_ID, request
if resp.error
# The API executed, but the script returned an error.
# Extract the first (and only) set of error details. The values of this
# object are the script's 'errorMessage' and 'errorType', and an array of
# stack trace elements.
error = resp.error.details[0]
puts "Script error message: #{error['errorMessage']}"
if error["scriptStackTraceElements"]
# There may not be a stacktrace if the script didn't start executing.
puts "Script error stacktrace:"
error["scriptStackTraceElements"].each do |trace|
puts "\t#{trace['function']}: #{trace['lineNumber']}"
end
end
else
# The structure of the result will depend upon what the Apps Script function
# returns. Here, the function returns an Apps Script Object with String keys
# and values, and so the result is treated as a Ruby hash (folderSet).
folder_set = resp.response["result"]
if folder_set.empty?
puts "No folders returned!"
else
puts "Folders under your root folder:"
folder_set.each do |id, folder|
puts "\t#{folder} (#{id})"
end
end
end
rescue Google::Apis::ClientError
# The API encountered a problem before the script started executing.
puts "Error calling API!"
end
# [END apps_script_api_execute]
| 35.048387 | 80 | 0.71422 |
e22c0af64711a0d2d4bdf5176656af9a9fc04cad | 2,273 | require 'spec_helper'
resource "Notes" do
let(:user) { users(:owner) }
let(:note) { events(:note_on_hdfs_file) }
let(:hdfs_file) { HdfsEntry.files.first }
let(:attachment) { attachments(:sql) }
before do
log_in user
end
post "/notes" do
parameter :body, "Text body of the note"
parameter :entity_type, "Type of object the note is being posted on"
parameter :entity_id, "Id of the object the note is being posted on"
parameter :is_insight, "Promote this note to an insight?"
let(:body) { note.body }
let(:gpdb_data_source) { data_sources(:owners) }
let(:entity_type) { "gpdb_data_source" }
let(:entity_id) { gpdb_data_source.id }
example_request "Post a new note/insight on an entity" do
status.should == 201
end
end
put "/notes/:id" do
parameter :id, "Note id"
parameter :body, "New text body of the note"
required_parameters :id
let(:id) { note.id }
let(:body) { "New text" }
example_request "Changes the body of a note" do
status.should == 200
end
end
delete "/notes/:id" do
parameter :id, "Note id"
required_parameters :id
let(:id) { note.id }
example_request "Delete a note" do
status.should == 200
end
end
post "/notes/:note_id/attachments" do
parameter :note_id, "Note id"
parameter :contents, "File contents"
required_parameters :note_id, :contents
let(:note_id) { note.id }
let(:contents) { test_file("small1.gif") }
example_request "Attach the contents of a file to a note" do
status.should == 200
end
end
post "/notes/:note_id/attachments" do
parameter :note_id, "Note id"
parameter :svg_data, "SVG File contents"
required_parameters :note_id, :svg_data
let(:note_id) { note.id }
let(:svg_data) { test_file("SVG-logo.svg").read }
example_request "Attach a visualization to a note" do
status.should == 200
end
end
get "/notes/:note_id/attachments/:id" do
parameter :note_id, "Note id"
parameter :id, "Attachment id"
required_parameters :note_id, :id
let(:note_id) { note.id }
let(:id) { attachment.id }
example_request "Get the contents of an attachment" do
status.should == 200
end
end
end
| 23.43299 | 72 | 0.649362 |
5d9d7f61ae5f79b40ca53d75a44575fb1843ca26 | 974 | require 'test_helper'
class PostTest < ActiveSupport::TestCase
def setup
@user = users(:michael)
# This code is not idiomatically correct.
@post = Post.new(subject: "Macbook Pro on sale!", price: 200, city: "Fremont", state: "California", content: "Lorem ipsum", user_id: @user.id)
end
test "should be valid" do
assert @post.valid?
end
test "user id should be present" do
@post.user_id = nil
assert_not @post.valid?
end
test "subject should be present" do
@post.subject = " "
assert_not @post.valid?
end
test "price should be present" do
@post.price = nil
assert_not @post.valid?
end
test "content should be present" do
@post.content = " "
assert_not @post.valid?
end
test "content should be at most 140 characters" do
@post.content = "a" * 141
assert_not @post.valid?
end
test "order should be most recent first" do
assert_equal posts(:most_recent), Post.first
end
end
| 22.651163 | 146 | 0.663244 |
bb2059c8acafcde4c4d26008cde548c8989f80e4 | 1,501 | # encoding: utf-8
# Code generated by Microsoft (R) AutoRest Code Generator 1.0.1.0
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
module MobileCenterApi
module Models
#
# Model object.
#
#
class XamarinSolution
# @return [String] Path to solution
attr_accessor :path
# @return [Array<String>] Solution configurations
attr_accessor :configurations
#
# Mapper for XamarinSolution class as Ruby Hash.
# This will be used for serialization/deserialization.
#
def self.mapper()
{
required: false,
serialized_name: 'XamarinSolution',
type: {
name: 'Composite',
class_name: 'XamarinSolution',
model_properties: {
path: {
required: true,
serialized_name: 'path',
type: {
name: 'String'
}
},
configurations: {
required: true,
serialized_name: 'configurations',
type: {
name: 'Sequence',
element: {
required: false,
serialized_name: 'StringElementType',
type: {
name: 'String'
}
}
}
}
}
}
}
end
end
end
end
| 25.016667 | 70 | 0.465023 |
1c4734fa99e468c743b71cd194bd03b59139a6c9 | 81 | module Fastlane
module MergeJunitReport
VERSION = '0.5.0'.freeze
end
end
| 13.5 | 28 | 0.716049 |
3895e517a4f30cda05af47e4c6652186e3c95f5a | 862 | require File.dirname(__FILE__) + "/../test_helper"
class RadiantLayoutsTest < Test::Unit::TestCase
fixtures :layouts
class ControllerWithRadiantLayout < ApplicationController
radiant_layout 'main'
end
class ControllerWithRadiantLayoutBlock < ApplicationController
radiant_layout {|c| c.action_name == "index" ? "main" : "utf8" }
end
def test_should_have_radiant_layout_attribute
assert_equal 'main', ControllerWithRadiantLayout.read_inheritable_attribute('radiant_layout')
assert_equal 'radiant', ControllerWithRadiantLayout.read_inheritable_attribute('layout')
end
def test_should_have_radiant_layout_block
assert_kind_of Proc, ControllerWithRadiantLayoutBlock.read_inheritable_attribute('radiant_layout')
assert_equal 'radiant', ControllerWithRadiantLayoutBlock.read_inheritable_attribute('layout')
end
end
| 35.916667 | 102 | 0.803944 |
117cbec26a4821280f2834ea92342ca5c0ac8314 | 335 | # Dependencies
require 'kss'
require 'redcarpet'
require 'pygments.rb'
require 'haml'
# Styleguide Engine
require "styleguide/engine"
module Styleguide
autoload :Configuration, 'styleguide/configuration'
def self.setup
@config = Styleguide::Configuration.new
yield @config
end
def self.config
@config
end
end
| 15.227273 | 53 | 0.740299 |
bf4c569cfc4001b965efd0c782ecb23fcf81faf9 | 1,740 | describe :hash_each, shared: true do
it "yields a [[key, value]] Array for each pair to a block expecting |*args|" do
all_args = []
{ 1 => 2, 3 => 4 }.send(@method) { |*args| all_args << args }
all_args.sort.should == [[[1, 2]], [[3, 4]]]
end
it "yields the key and value of each pair to a block expecting |key, value|" do
r = {}
h = { a: 1, b: 2, c: 3, d: 5 }
h.send(@method) { |k,v| r[k.to_s] = v.to_s }.should equal(h)
r.should == { "a" => "1", "b" => "2", "c" => "3", "d" => "5" }
end
it "yields the key only to a block expecting |key,|" do
ary = []
h = { "a" => 1, "b" => 2, "c" => 3 }
h.send(@method) { |k,| ary << k }
ary.sort.should == ["a", "b", "c"]
end
it "uses the same order as keys() and values()" do
h = { a: 1, b: 2, c: 3, d: 5 }
keys = []
values = []
h.send(@method) do |k, v|
keys << k
values << v
end
keys.should == h.keys
values.should == h.values
end
# Confirming the argument-splatting works from child class for both k, v and [k, v]
it "properly expands (or not) child class's 'each'-yielded args" do
cls1 = Class.new(Hash) do
attr_accessor :k_v
def each
super do |k, v|
@k_v = [k, v]
yield k, v
end
end
end
cls2 = Class.new(Hash) do
attr_accessor :k_v
def each
super do |k, v|
@k_v = [k, v]
yield([k, v])
end
end
end
obj1 = cls1.new
obj1['a'] = 'b'
obj1.map {|k, v| [k, v]}.should == [['a', 'b']]
obj1.k_v.should == ['a', 'b']
obj2 = cls2.new
obj2['a'] = 'b'
obj2.map {|k, v| [k, v]}.should == [['a', 'b']]
obj2.k_v.should == ['a', 'b']
end
end
| 25.217391 | 85 | 0.482759 |
5de3e793d86b07ff1ae8a0f220ab9433663ecc3b | 268 | require 'spec_helper'
describe Spree::GiftCardTransaction do
it {should belong_to(:gift_card)}
it {should belong_to(:order)}
it {should validate_presence_of(:amount)}
it {should validate_presence_of(:gift_card)}
it {should validate_presence_of(:order)}
end
| 26.8 | 46 | 0.772388 |
911a7f5d3586787afc41efb191a2455c8a37f35f | 6,455 | # frozen_string_literal: true
module Gitlab
module Ci
module Reports
module Security
class Finding
include ::VulnerabilityFindingHelpers
attr_reader :compare_key
attr_reader :confidence
attr_reader :identifiers
attr_reader :flags
attr_reader :links
attr_reader :location
attr_reader :evidence
attr_reader :metadata_version
attr_reader :name
attr_reader :old_location
attr_reader :project_fingerprint
attr_reader :report_type
attr_reader :scanner
attr_reader :scan
attr_reader :severity
attr_accessor :uuid
attr_accessor :overridden_uuid
attr_reader :remediations
attr_reader :details
attr_reader :signatures
attr_reader :project_id
attr_reader :original_data
delegate :file_path, :start_line, :end_line, to: :location
alias_method :cve, :compare_key
def initialize(compare_key:, identifiers:, flags: [], links: [], remediations: [], location:, evidence:, metadata_version:, name:, original_data:, report_type:, scanner:, scan:, uuid:, confidence: nil, severity: nil, details: {}, signatures: [], project_id: nil, vulnerability_finding_signatures_enabled: false) # rubocop:disable Metrics/ParameterLists
@compare_key = compare_key
@confidence = confidence
@identifiers = identifiers
@flags = flags
@links = links
@location = location
@evidence = evidence
@metadata_version = metadata_version
@name = name
@original_data = original_data
@report_type = report_type
@scanner = scanner
@scan = scan
@severity = severity
@uuid = uuid
@remediations = remediations
@details = details
@signatures = signatures
@project_id = project_id
@vulnerability_finding_signatures_enabled = vulnerability_finding_signatures_enabled
@project_fingerprint = generate_project_fingerprint
end
def to_hash
%i[
compare_key
confidence
identifiers
flags
links
location
evidence
metadata_version
name
project_fingerprint
raw_metadata
report_type
scanner
scan
severity
uuid
details
signatures
description
message
cve
solution
].each_with_object({}) do |key, hash|
hash[key] = public_send(key) # rubocop:disable GitlabSecurity/PublicSend
end
end
def primary_identifier
identifiers.first
end
def update_location(new_location)
@old_location = location
@location = new_location
end
def unsafe?(severity_levels, report_types)
severity.to_s.in?(severity_levels) && (report_types.blank? || report_type.to_s.in?(report_types) )
end
def eql?(other)
return false unless report_type == other.report_type && primary_identifier_fingerprint == other.primary_identifier_fingerprint
if @vulnerability_finding_signatures_enabled
matches_signatures(other.signatures, other.uuid)
else
location.fingerprint == other.location.fingerprint
end
end
def hash
if @vulnerability_finding_signatures_enabled && !signatures.empty?
highest_signature = signatures.max_by(&:priority)
report_type.hash ^ highest_signature.signature_hex.hash ^ primary_identifier_fingerprint.hash
else
report_type.hash ^ location.fingerprint.hash ^ primary_identifier_fingerprint.hash
end
end
def valid?
scanner.present? && primary_identifier.present? && location.present? && uuid.present?
end
def keys
@keys ||= identifiers.reject(&:type_identifier?).flat_map do |identifier|
location_fingerprints.map do |location_fingerprint|
FindingKey.new(location_fingerprint: location_fingerprint, identifier_fingerprint: identifier.fingerprint)
end
end.push(uuid)
end
def primary_identifier_fingerprint
primary_identifier&.fingerprint
end
def <=>(other)
if severity == other.severity
compare_key <=> other.compare_key
else
::Enums::Vulnerability.severity_levels[other.severity] <=>
::Enums::Vulnerability.severity_levels[severity]
end
end
def scanner_order_to(other)
return 1 unless scanner
return -1 unless other&.scanner
scanner <=> other.scanner
end
def has_signatures?
signatures.present?
end
def raw_metadata
@raw_metadata ||= original_data.to_json
end
def description
original_data['description']
end
def message
original_data['message']
end
def solution
original_data['solution']
end
def location_data
original_data['location']
end
# Returns either the max priority signature hex
# or the location fingerprint
def location_fingerprint
location_fingerprints.first
end
private
def generate_project_fingerprint
Digest::SHA1.hexdigest(compare_key)
end
def location_fingerprints
@location_fingerprints ||= signature_hexes << location&.fingerprint
end
# Returns the signature hexes in reverse priority order
def signature_hexes
return [] unless @vulnerability_finding_signatures_enabled && signatures.present?
signatures.sort_by(&:priority).map(&:signature_hex).reverse
end
end
end
end
end
end
| 31.334951 | 362 | 0.577072 |
1872d6a0b8ee363caa368c44ad0c396a7e20357d | 1,624 | ##
## OkComputer provides customizable health check endpoints
## (https://github.com/sportngin/okcomputer).
## It is an important piece of the OpsCare stack.
## Don't edit this file unless you know what you are doing,
## it could result in an undeployable app.
##
require "securerandom"
# If the envvar is not set, generate a random string.
# It will be inaccessible, but at least secured.
if ENV["HEALTHCHECK_TOKEN"].blank?
healthcheck_token = SecureRandom.hex(32)
Rails.logger.info "No HEALTHCHECK_TOKEN envvar found. Staring OkComuter " \
"with a generated one: #{healthcheck_token}"
else
healthcheck_token = ENV["HEALTHCHECK_TOKEN"]
end
# Mount the health checks at a tokenized url
OkComputer.mount_at = "health_checks_#{healthcheck_token}"
# The common checks we would want
# See here for othe built in checks:
# https://github.com/sportngin/okcomputer/tree/master/lib/ok_computer/built_in_checks
OkComputer::Registry.register "db", OkComputer::ActiveRecordCheck.new
OkComputer::Registry.register "revision", OkComputer::AppVersionCheck.new
OkComputer::Registry.register "ruby_version", OkComputer::RubyVersionCheck.new
## To add custom checks, uncomment and adapt the lines bellow:
## beware that a false return value will cause the deploys to fail.
## (example from documentation)
# class MyCustomCheck < OkComputer::Check
# def check
# if rand(10).even?
# mark_message "Even is great!"
# else
# mark_failure
# mark_message "We don't like odd numbers"
# end
# end
# end
# OkComputer::Registry.register "check_for_odds", MyCustomCheck.new
| 36.088889 | 85 | 0.739532 |
38ecef20133cd5940684937976843c5fdc3eb28a | 949 | class Github
def initialize(user)
@user = user
end
### would prefer to not pass in an argument of the user, but that's what allowed me to test for failure condition of api
def top_starred
begin
results = RestClient::Request.execute(method: :get, url: "https://api.github.com/search/repositories?q=user:#{@user}&sort=stars&order=desc&per_page=100", headers: {Authorization: ENV['GITHUB_ACCESS_TOKEN']})
JSON.parse(results)['items'].first(5)
rescue RestClient::ExceptionWithResponse => e
puts e.response
e.response
end
end
def recently_updated
begin
results = RestClient::Request.execute(method: :get, url: "https://api.github.com/search/repositories?q=user:#{@user}&sort=updated", headers: {Authorization: ENV['GITHUB_ACCESS_TOKEN']})
JSON.parse(results)['items'].first(5)
rescue RestClient::ExceptionWithResponse => e
puts e.response
e.response
end
end
end
| 35.148148 | 213 | 0.696523 |
bf8e034aeeeb375a0e0ea9bdfe9f1150bf28602a | 22,335 | #! /usr/bin/env ruby
require 'spec_helper'
require 'oregano/pops'
require 'oregano_spec/pops'
require_relative '../parser/parser_rspec_helper'
describe "validating 4x" do
include ParserRspecHelper
include OreganoSpec::Pops
let(:acceptor) { Oregano::Pops::Validation::Acceptor.new() }
let(:validator) { Oregano::Pops::Validation::ValidatorFactory_4_0.new().validator(acceptor) }
def validate(factory)
validator.validate(factory.model)
acceptor
end
it 'should raise error for illegal class names' do
expect(validate(parse('class aaa::_bbb {}'))).to have_issue(Oregano::Pops::Issues::ILLEGAL_DEFINITION_NAME)
expect(validate(parse('class Aaa {}'))).to have_issue(Oregano::Pops::Issues::ILLEGAL_DEFINITION_NAME)
expect(validate(parse('class ::aaa {}'))).to have_issue(Oregano::Pops::Issues::ILLEGAL_DEFINITION_NAME)
end
it 'should raise error for illegal define names' do
expect(validate(parse('define aaa::_bbb {}'))).to have_issue(Oregano::Pops::Issues::ILLEGAL_DEFINITION_NAME)
expect(validate(parse('define Aaa {}'))).to have_issue(Oregano::Pops::Issues::ILLEGAL_DEFINITION_NAME)
expect(validate(parse('define ::aaa {}'))).to have_issue(Oregano::Pops::Issues::ILLEGAL_DEFINITION_NAME)
end
it 'should raise error for illegal function names' do
expect(validate(parse('function aaa::_bbb() {}'))).to have_issue(Oregano::Pops::Issues::ILLEGAL_DEFINITION_NAME)
expect(validate(parse('function Aaa() {}'))).to have_issue(Oregano::Pops::Issues::ILLEGAL_DEFINITION_NAME)
expect(validate(parse('function ::aaa() {}'))).to have_issue(Oregano::Pops::Issues::ILLEGAL_DEFINITION_NAME)
end
it 'should raise error for illegal type names' do
expect(validate(parse('type ::Aaa = Any'))).to have_issue(Oregano::Pops::Issues::ILLEGAL_DEFINITION_NAME)
end
it 'should raise error for illegal variable names' do
expect(validate(fqn('Aaa').var())).to have_issue(Oregano::Pops::Issues::ILLEGAL_VAR_NAME)
expect(validate(fqn('AAA').var())).to have_issue(Oregano::Pops::Issues::ILLEGAL_VAR_NAME)
expect(validate(fqn('aaa::_aaa').var())).to have_issue(Oregano::Pops::Issues::ILLEGAL_VAR_NAME)
end
it 'should not raise error for variable name with underscore first in first name segment' do
expect(validate(fqn('_aa').var())).to_not have_issue(Oregano::Pops::Issues::ILLEGAL_VAR_NAME)
expect(validate(fqn('::_aa').var())).to_not have_issue(Oregano::Pops::Issues::ILLEGAL_VAR_NAME)
end
context 'with the default settings for --strict' do
it 'produces a warning for duplicate keys in a literal hash' do
acceptor = validate(parse('{ a => 1, a => 2 }'))
expect(acceptor.warning_count).to eql(1)
expect(acceptor.error_count).to eql(0)
expect(acceptor).to have_issue(Oregano::Pops::Issues::DUPLICATE_KEY)
end
end
context 'with --strict set to warning' do
before(:each) { Oregano[:strict] = :warning }
it 'produces a warning for duplicate keys in a literal hash' do
acceptor = validate(parse('{ a => 1, a => 2 }'))
expect(acceptor.warning_count).to eql(1)
expect(acceptor.error_count).to eql(0)
expect(acceptor).to have_issue(Oregano::Pops::Issues::DUPLICATE_KEY)
end
it 'produces a warning for virtual class resource' do
acceptor = validate(parse('@class { test: }'))
expect(acceptor.warning_count).to eql(1)
expect(acceptor.error_count).to eql(0)
expect(acceptor).to have_issue(Oregano::Pops::Issues::CLASS_NOT_VIRTUALIZABLE)
end
it 'produces a warning for exported class resource' do
acceptor = validate(parse('@@class { test: }'))
expect(acceptor.warning_count).to eql(1)
expect(acceptor.error_count).to eql(0)
expect(acceptor).to have_issue(Oregano::Pops::Issues::CLASS_NOT_VIRTUALIZABLE)
end
end
context 'with --strict set to error' do
before(:each) { Oregano[:strict] = :error }
it 'produces an error for duplicate keys in a literal hash' do
acceptor = validate(parse('{ a => 1, a => 2 }'))
expect(acceptor.warning_count).to eql(0)
expect(acceptor.error_count).to eql(1)
expect(acceptor).to have_issue(Oregano::Pops::Issues::DUPLICATE_KEY)
end
it 'produces an error for virtual class resource' do
acceptor = validate(parse('@class { test: }'))
expect(acceptor.warning_count).to eql(0)
expect(acceptor.error_count).to eql(1)
expect(acceptor).to have_issue(Oregano::Pops::Issues::CLASS_NOT_VIRTUALIZABLE)
end
it 'does not produce an error for regular class resource' do
acceptor = validate(parse('class { test: }'))
expect(acceptor.warning_count).to eql(0)
expect(acceptor.error_count).to eql(0)
expect(acceptor).not_to have_issue(Oregano::Pops::Issues::CLASS_NOT_VIRTUALIZABLE)
end
it 'produces an error for exported class resource' do
acceptor = validate(parse('@@class { test: }'))
expect(acceptor.warning_count).to eql(0)
expect(acceptor.error_count).to eql(1)
expect(acceptor).to have_issue(Oregano::Pops::Issues::CLASS_NOT_VIRTUALIZABLE)
end
end
context 'with --strict set to off' do
before(:each) { Oregano[:strict] = :off }
it 'does not produce an error or warning for duplicate keys in a literal hash' do
acceptor = validate(parse('{ a => 1, a => 2 }'))
expect(acceptor.warning_count).to eql(0)
expect(acceptor.error_count).to eql(0)
expect(acceptor).to_not have_issue(Oregano::Pops::Issues::DUPLICATE_KEY)
end
end
context 'irrespective of --strict' do
it 'produces an error for duplicate default in a case expression' do
acceptor = validate(parse('case 1 { default: {1} default : {2} }'))
expect(acceptor.warning_count).to eql(0)
expect(acceptor.error_count).to eql(1)
expect(acceptor).to have_issue(Oregano::Pops::Issues::DUPLICATE_DEFAULT)
end
it 'produces an error for duplicate default in a selector expression' do
acceptor = validate(parse(' 1 ? { default => 1, default => 2 }'))
expect(acceptor.warning_count).to eql(0)
expect(acceptor.error_count).to eql(1)
expect(acceptor).to have_issue(Oregano::Pops::Issues::DUPLICATE_DEFAULT)
end
it 'produces a warning for virtual class resource' do
acceptor = validate(parse('@class { test: }'))
expect(acceptor.warning_count).to eql(1)
expect(acceptor.error_count).to eql(0)
expect(acceptor).to have_issue(Oregano::Pops::Issues::CLASS_NOT_VIRTUALIZABLE)
end
it 'produces a warning for exported class resource' do
acceptor = validate(parse('@@class { test: }'))
expect(acceptor.warning_count).to eql(1)
expect(acceptor.error_count).to eql(0)
expect(acceptor).to have_issue(Oregano::Pops::Issues::CLASS_NOT_VIRTUALIZABLE)
end
end
context 'for non productive expressions' do
[ '1',
'3.14',
"'a'",
'"a"',
'"${$a=10}"', # interpolation with side effect
'false',
'true',
'default',
'undef',
'[1,2,3]',
'{a=>10}',
'if 1 {2}',
'if 1 {2} else {3}',
'if 1 {2} elsif 3 {4}',
'unless 1 {2}',
'unless 1 {2} else {3}',
'1 ? 2 => 3',
'1 ? { 2 => 3}',
'-1',
'-foo()', # unary minus on productive
'1+2',
'1<2',
'(1<2)',
'!true',
'!foo()', # not on productive
'$a',
'$a[1]',
'name',
'Type',
'Type[foo]'
].each do |expr|
it "produces error for non productive: #{expr}" do
source = "#{expr}; $a = 10"
expect(validate(parse(source))).to have_issue(Oregano::Pops::Issues::IDEM_EXPRESSION_NOT_LAST)
end
it "does not produce error when last for non productive: #{expr}" do
source = " $a = 10; #{expr}"
expect(validate(parse(source))).to_not have_issue(Oregano::Pops::Issues::IDEM_EXPRESSION_NOT_LAST)
end
end
[
'if 1 {$a = 1}',
'if 1 {2} else {$a=1}',
'if 1 {2} elsif 3 {$a=1}',
'unless 1 {$a=1}',
'unless 1 {2} else {$a=1}',
'$a = 1 ? 2 => 3',
'$a = 1 ? { 2 => 3}',
'Foo[a] -> Foo[b]',
'($a=1)',
'foo()',
'$a.foo()'
].each do |expr|
it "does not produce error when for productive: #{expr}" do
source = "#{expr}; $x = 1"
expect(validate(parse(source))).to_not have_issue(Oregano::Pops::Issues::IDEM_EXPRESSION_NOT_LAST)
end
end
['class', 'define', 'node'].each do |type|
it "flags non productive expression last in #{type}" do
source = <<-SOURCE
#{type} nope {
1
}
end
SOURCE
expect(validate(parse(source))).to have_issue(Oregano::Pops::Issues::IDEM_NOT_ALLOWED_LAST)
end
it "detects a resource declared without title in #{type} when it is the only declaration present" do
source = <<-SOURCE
#{type} nope {
notify { message => 'Nope' }
}
SOURCE
expect(validate(parse(source))).to have_issue(Oregano::Pops::Issues::RESOURCE_WITHOUT_TITLE)
end
it "detects a resource declared without title in #{type} when it is in between other declarations" do
source = <<-SOURCE
#{type} nope {
notify { succ: message => 'Nope' }
notify { message => 'Nope' }
notify { pred: message => 'Nope' }
}
SOURCE
expect(validate(parse(source))).to have_issue(Oregano::Pops::Issues::RESOURCE_WITHOUT_TITLE)
end
it "detects a resource declared without title in #{type} when it is declarated first" do
source = <<-SOURCE
#{type} nope {
notify { message => 'Nope' }
notify { pred: message => 'Nope' }
}
SOURCE
expect(validate(parse(source))).to have_issue(Oregano::Pops::Issues::RESOURCE_WITHOUT_TITLE)
end
it "detects a resource declared without title in #{type} when it is declarated last" do
source = <<-SOURCE
#{type} nope {
notify { succ: message => 'Nope' }
notify { message => 'Nope' }
}
SOURCE
expect(validate(parse(source))).to have_issue(Oregano::Pops::Issues::RESOURCE_WITHOUT_TITLE)
end
end
end
context 'for reserved words' do
['private', 'attr'].each do |word|
it "produces an error for the word '#{word}'" do
source = "$a = #{word}"
expect(validate(parse(source))).to have_issue(Oregano::Pops::Issues::RESERVED_WORD)
end
end
end
context 'for reserved type names' do
[# type/Type, is a reserved name but results in syntax error because it is a keyword in lower case form
'any',
'unit',
'scalar',
'boolean',
'numeric',
'integer',
'float',
'collection',
'array',
'hash',
'tuple',
'struct',
'variant',
'optional',
'enum',
'regexp',
'pattern',
'runtime',
].each do |name|
it "produces an error for 'class #{name}'" do
source = "class #{name} {}"
expect(validate(parse(source))).to have_issue(Oregano::Pops::Issues::RESERVED_TYPE_NAME)
end
it "produces an error for 'define #{name}'" do
source = "define #{name} {}"
expect(validate(parse(source))).to have_issue(Oregano::Pops::Issues::RESERVED_TYPE_NAME)
end
end
end
context 'for keywords' do
it "should allow using the 'type' as the name of a function with no parameters" do
source = "type()"
expect(validate(parse(source))).not_to have_any_issues
end
it "should allow using the keyword 'type' as the name of a function with parameters" do
source = "type('a', 'b')"
expect(validate(parse(source))).not_to have_any_issues
end
it "should allow using the 'type' as the name of a function with no parameters and a block" do
source = "type() |$x| { $x }"
expect(validate(parse(source))).not_to have_any_issues
end
it "should allow using the keyword 'type' as the name of a function with parameters and a block" do
source = "type('a', 'b') |$x| { $x }"
expect(validate(parse(source))).not_to have_any_issues
end
end
context 'for parameter names' do
['class', 'define'].each do |word|
it "should require that #{word} parameter names are unique" do
expect(validate(parse("#{word} foo($a = 10, $a = 20) {}"))).to have_issue(Oregano::Pops::Issues::DUPLICATE_PARAMETER)
end
end
it "should require that template parameter names are unique" do
expect(validate(parse_epp("<%-| $a, $a |-%><%= $a == doh %>"))).to have_issue(Oregano::Pops::Issues::DUPLICATE_PARAMETER)
end
end
context 'for parameter defaults' do
['class', 'define'].each do |word|
it "should not permit assignments in #{word} parameter default expressions" do
expect { parse("#{word} foo($a = $x = 10) {}") }.to raise_error(Oregano::ParseErrorWithIssue, /Syntax error at '='/)
end
end
['class', 'define'].each do |word|
it "should not permit assignments in #{word} parameter default nested expressions" do
expect(validate(parse("#{word} foo($a = [$x = 10]) {}"))).to have_issue(Oregano::Pops::Issues::ILLEGAL_ASSIGNMENT_CONTEXT)
end
it "should not permit assignments to subsequently declared parameters in #{word} parameter default nested expressions" do
expect(validate(parse("#{word} foo($a = ($b = 3), $b = 5) {}"))).to have_issue(Oregano::Pops::Issues::ILLEGAL_ASSIGNMENT_CONTEXT)
end
it "should not permit assignments to previously declared parameters in #{word} parameter default nested expressions" do
expect(validate(parse("#{word} foo($a = 10, $b = ($a = 10)) {}"))).to have_issue(Oregano::Pops::Issues::ILLEGAL_ASSIGNMENT_CONTEXT)
end
it "should permit assignments in #{word} parameter default inside nested lambda expressions" do
expect(validate(parse(
"#{word} foo($a = [1,2,3], $b = 0, $c = $a.map |$x| { $b = $x; $b * $a.reduce |$x, $y| {$x + $y}}) {}"))).not_to(
have_issue(Oregano::Pops::Issues::ILLEGAL_ASSIGNMENT_CONTEXT))
end
end
end
context 'for reserved parameter names' do
['name', 'title'].each do |word|
it "produces an error when $#{word} is used as a parameter in a class" do
source = "class x ($#{word}) {}"
expect(validate(parse(source))).to have_issue(Oregano::Pops::Issues::RESERVED_PARAMETER)
end
it "produces an error when $#{word} is used as a parameter in a define" do
source = "define x ($#{word}) {}"
expect(validate(parse(source))).to have_issue(Oregano::Pops::Issues::RESERVED_PARAMETER)
end
end
end
context 'for numeric parameter names' do
['1', '0x2', '03'].each do |word|
it "produces an error when $#{word} is used as a parameter in a class" do
source = "class x ($#{word}) {}"
expect(validate(parse(source))).to have_issue(Oregano::Pops::Issues::ILLEGAL_NUMERIC_PARAMETER)
end
end
end
context 'for badly formed non-numeric parameter names' do
['Ateam', 'a::team'].each do |word|
it "produces an error when $#{word} is used as a parameter in a class" do
source = "class x ($#{word}) {}"
expect(validate(parse(source))).to have_issue(Oregano::Pops::Issues::ILLEGAL_PARAM_NAME)
end
it "produces an error when $#{word} is used as a parameter in a define" do
source = "define x ($#{word}) {}"
expect(validate(parse(source))).to have_issue(Oregano::Pops::Issues::ILLEGAL_PARAM_NAME)
end
it "produces an error when $#{word} is used as a parameter in a lambda" do
source = "with() |$#{word}| {}"
expect(validate(parse(source))).to have_issue(Oregano::Pops::Issues::ILLEGAL_PARAM_NAME)
end
end
end
context 'top level constructs' do
def issue(at_top)
at_top ? Oregano::Pops::Issues::NOT_ABSOLUTE_TOP_LEVEL : Oregano::Pops::Issues::NOT_TOP_LEVEL
end
# Top level. Defines the expressions that are tested inside of other things
{
'a class' => ['class x{}', false],
'a define' => ['define x{}', false],
'a node' => ['node x{}', false],
'a function' => ['function x() {}', true],
'a type alias' => ['type A = Data', true],
'a type alias for a complex type' => ['type C = Hash[String[1],Integer]', true],
'a type definition' => ['type A {}', true]
}.each_pair do |word, (decl, at_top)|
# Nesting level. Defines how each of the top level expressions are nested in
# another expression
{
'a define' => ["define y{ #{decl} }", at_top],
'a function' => ["function y() { #{decl} }", at_top],
'a type definition' => ["type A { #{decl} }", at_top],
'an if expression' => ["if true { #{decl} }", false],
'an if-else expression' => ["if false {} else { #{decl} }", false],
'an unless' => ["unless false { #{decl} }", false]
}.each_pair do |nester, (source, abs_top)|
# Tests each top level expression in each nested expression
it "produces an error when #{word} is nested in #{nester}" do
expect(validate(parse(source))).to have_issue(issue(abs_top))
end
end
# Test that the expression can exist anywhere in a top level block
it "will allow #{word} as the only statement in a top level block" do
expect(validate(parse(decl))).not_to have_issue(issue(at_top))
end
it "will allow #{word} as the last statement in a top level block" do
source = "$a = 10\n#{decl}"
expect(validate(parse(source))).not_to have_issue(issue(at_top))
end
it "will allow #{word} as the first statement in a top level block" do
source = "#{decl}\n$a = 10"
expect(validate(parse(source))).not_to have_issue(issue(at_top))
end
it "will allow #{word} in between other statements in a top level block" do
source = "$a = 10\n#{decl}\n$b = 20"
expect(validate(parse(source))).not_to have_issue(issue(at_top))
end
end
context 'that are type aliases' do
it 'raises errors when RHS is a name that is an invalid reference' do
source = 'type MyInt = integer'
expect { parse(source) }.to raise_error(/Syntax error at 'integer'/)
end
it 'raises errors when RHS is an AccessExpression with a name that is an invalid reference on LHS' do
source = 'type IntegerArray = array[Integer]'
expect { parse(source) }.to raise_error(/Syntax error at 'array'/)
end
end
context 'that are functions' do
it 'accepts typed parameters' do
source = <<-CODE
function f(Integer $a) { $a }
CODE
expect(validate(parse(source))).not_to have_any_issues
end
it 'accepts return types' do
source = <<-CODE
function f() >> Integer { 42 }
CODE
expect(validate(parse(source))).not_to have_any_issues
end
it 'accepts block with return types' do
source = <<-CODE
map([1,2]) |Integer $x| >> Integer { $x + 3 }
CODE
expect(validate(parse(source))).not_to have_any_issues
end
end
context 'that are type mappings' do
it 'accepts a valid type mapping expression' do
source = <<-CODE
type Runtime[ruby, 'MyModule::MyObject'] = MyPackage::MyObject
notice(true)
CODE
expect(validate(parse(source))).not_to have_any_issues
end
it 'accepts a valid regexp based type mapping expression' do
source = <<-CODE
type Runtime[ruby, [/^MyPackage::(\w+)$/, 'MyModule::\1']] = [/^MyModule::(\w+)$/, 'MyPackage::\1']
notice(true)
CODE
expect(validate(parse(source))).not_to have_any_issues
end
it 'raises an error when a regexp based Runtime type is paired with a Oregano Type' do
source = <<-CODE
type Runtime[ruby, [/^MyPackage::(\w+)$/, 'MyModule::\1']] = MyPackage::MyObject
notice(true)
CODE
expect(validate(parse(source))).to have_issue(Oregano::Pops::Issues::ILLEGAL_REGEXP_TYPE_MAPPING)
end
it 'raises an error when a singleton Runtime type is paired with replacement pattern' do
source = <<-CODE
type Runtime[ruby, 'MyModule::MyObject'] = [/^MyModule::(\w+)$/, 'MyPackage::\1']
notice(true)
CODE
expect(validate(parse(source))).to have_issue(Oregano::Pops::Issues::ILLEGAL_SINGLE_TYPE_MAPPING)
end
it 'raises errors unless LHS is Runtime type' do
source = <<-CODE
type Pattern[/^MyPackage::(\w+)$/, 'MyModule::\1'] = [/^MyModule::(\w+)$/, 'MyPackage::\1']
notice(true)
CODE
expect(validate(parse(source))).to have_issue(Oregano::Pops::Issues::UNSUPPORTED_EXPRESSION)
end
end
end
context "capability annotations" do
['produces', 'consumes'].each do |word|
it "rejects illegal resource types in #{word} clauses" do
expect(validate(parse("foo produces Bar {}"))).to have_issue(Oregano::Pops::Issues::ILLEGAL_CLASSREF)
end
it "accepts legal resource and capability types in #{word} clauses" do
expect(validate(parse("Foo produces Bar {}"))).to_not have_issue(Oregano::Pops::Issues::ILLEGAL_CLASSREF)
expect(validate(parse("Mod::Foo produces ::Mod2::Bar {}"))).to_not have_issue(Oregano::Pops::Issues::ILLEGAL_CLASSREF)
end
it "rejects illegal capability types in #{word} clauses" do
expect(validate(parse("Foo produces bar {}"))).to have_issue(Oregano::Pops::Issues::ILLEGAL_CLASSREF)
end
end
end
context 'literal values' do
it 'rejects a literal integer outside of max signed 64 bit range' do
expect(validate(parse("0x8000000000000000"))).to have_issue(Oregano::Pops::Issues::NUMERIC_OVERFLOW)
end
it 'rejects a literal integer outside of min signed 64 bit range' do
expect(validate(parse("-0x8000000000000001"))).to have_issue(Oregano::Pops::Issues::NUMERIC_OVERFLOW)
end
end
def parse(source)
Oregano::Pops::Parser::Parser.new.parse_string(source)
end
end
| 38.442341 | 139 | 0.628565 |
180ef72321bdefbe7512695daea500b6440b3d44 | 82 | # frozen_string_literal: true
module ToSentenceExclusive
VERSION = "1.0.1"
end
| 13.666667 | 29 | 0.768293 |
0343f95fa0d5db09b77c171d79d598f5af58eaef | 329 | require File.expand_path("../lib/php_extension_formula", __dir__)
class PhpAT72Recode < PhpExtensionFormula
extension_dsl "GNU Recode Extension"
conflicts_with "php-imap", :because => "because both share the same internal symbols"
depends_on "recode"
configure_arg "--with-recode=#{Formula["recode"].opt_prefix}"
end
| 27.416667 | 87 | 0.765957 |
1dba746e5466c38e0c769eeb8605082e68f6c9fe | 3,517 | require 'helper'
require 'inspec/resource'
require 'resources/aws/aws_iam_root_user'
require 'resource_support/aws'
require 'resources/aws/aws_iam_root_user'
class AwsIamRootUserTest < Minitest::Test
def setup
@mock_conn = Minitest::Mock.new
@mock_client = Minitest::Mock.new
@mock_conn.expect :iam_client, @mock_client
end
def test_has_access_key_returns_true_from_summary_account
test_summary_map = OpenStruct.new(
summary_map: { 'AccountAccessKeysPresent' => 1 },
)
@mock_client.expect :get_account_summary, test_summary_map
assert_equal true, AwsIamRootUser.new(@mock_conn).has_access_key?
end
def test_has_access_key_returns_false_from_summary_account
test_summary_map = OpenStruct.new(
summary_map: { 'AccountAccessKeysPresent' => 0 },
)
@mock_client.expect :get_account_summary, test_summary_map
assert_equal false, AwsIamRootUser.new(@mock_conn).has_access_key?
end
def test_has_mfa_enabled_returns_true_when_account_mfa_devices_is_one
test_summary_map = OpenStruct.new(
summary_map: { 'AccountMFAEnabled' => 1 },
)
@mock_client.expect :get_account_summary, test_summary_map
assert_equal true, AwsIamRootUser.new(@mock_conn).has_mfa_enabled?
end
def test_has_mfa_enabled_returns_false_when_account_mfa_devices_is_zero
test_summary_map = OpenStruct.new(
summary_map: { 'AccountMFAEnabled' => 0 },
)
@mock_client.expect :get_account_summary, test_summary_map
assert_equal false, AwsIamRootUser.new(@mock_conn).has_mfa_enabled?
end
def test_has_virtual_mfa_enabled_returns_true_when_account_vmfa_devices_is_one
test_list_virtual_mfa_devices = OpenStruct.new(
virtual_mfa_devices: [Aws::IAM::Types::VirtualMFADevice.new(
serial_number: 'arn:aws:iam::123456789011:mfa/root-account-mfa-device',
user: Aws::IAM::Types::User.new(
user_id: '123456789011',
arn: 'arn:aws:iam::123456789011:root',
)
)]
)
@mock_client.expect :list_virtual_mfa_devices, test_list_virtual_mfa_devices
assert_equal true, AwsIamRootUser.new(@mock_conn).has_virtual_mfa_enabled?
end
def test_has_virtual_mfa_enabled_returns_false_when_account_vmfa_devices_is_zero
test_list_virtual_mfa_devices = OpenStruct.new(
virtual_mfa_devices: []
)
@mock_client.expect :list_virtual_mfa_devices, test_list_virtual_mfa_devices
assert_equal false, AwsIamRootUser.new(@mock_conn).has_virtual_mfa_enabled?
end
def test_has_hardware_mfa_enabled_returns_true_when_account_hardware_devices_is_one
test_list_virtual_mfa_devices = OpenStruct.new(
virtual_mfa_devices: []
)
test_summary_map = OpenStruct.new(
summary_map: { 'AccountMFAEnabled' => 1 },
)
@mock_client.expect :list_virtual_mfa_devices, test_list_virtual_mfa_devices
@mock_client.expect :get_account_summary, test_summary_map
assert_equal true, AwsIamRootUser.new(@mock_conn).has_hardware_mfa_enabled?
end
def test_has_hardware_mfa_enabled_returns_false_when_account_hardware_devices_is_zero
test_list_virtual_mfa_devices = OpenStruct.new(
virtual_mfa_devices: []
)
test_summary_map = OpenStruct.new(
summary_map: { 'AccountMFAEnabled' => 0 },
)
@mock_client.expect :get_account_summary, test_summary_map
@mock_client.expect :list_virtual_mfa_devices, test_list_virtual_mfa_devices
assert_equal false, AwsIamRootUser.new(@mock_conn).has_hardware_mfa_enabled?
end
end
| 34.480392 | 87 | 0.770543 |
f8f3b6d7f61c0deaffda3bd2568d76a50c9f5252 | 982 | #
# To learn more about a Podspec see http://guides.cocoapods.org/syntax/podspec.html
#
Pod::Spec.new do |s|
s.name = 'flutter_facebook_login'
s.version = '0.0.1'
s.summary = 'A Flutter plugin for allowing users to authenticate with native Android & iOS Facebook login SDKs.'
s.description = <<-DESC
A Flutter plugin for allowing users to authenticate with native Android & iOS Facebook login SDKs.
DESC
s.homepage = 'http://example.com'
s.license = { :file => '../LICENSE' }
s.author = { 'Your Company' => '[email protected]' }
s.source = { :path => '.' }
s.source_files = 'Classes/**/*'
s.public_header_files = 'Classes/**/*.h'
s.dependency 'Flutter'
s.dependency 'FBSDKCoreKit', '4.39.1'
s.dependency 'FBSDKLoginKit', '4.39.1'
# https://github.com/flutter/flutter/issues/14161
s.static_framework = true
s.ios.deployment_target = '8.0'
end
| 36.37037 | 127 | 0.617108 |
79168181e7a089dbe66ddfba6c6bfbcbaf16b04a | 275 | require 'spec_helper'
describe Qbrick::SitemapsController, type: :controller do
routes { Qbrick::Engine.routes }
describe '#index' do
it 'should be able to send a xml file' do
@page = FactoryGirl.create :page
get :index, format: 'xml'
end
end
end
| 21.153846 | 57 | 0.676364 |
e969f357b83ff06c156beb2598a7649e67e1565b | 4,822 | #
# Author:: Matheus Francisco Barra Mina (<[email protected]>)
# © Copyright IBM Corporation 2015.
#
# LICENSE: MIT (http://opensource.org/licenses/MIT)
#
module Fog
module Softlayer
class Compute
class Mock
# Gets all Bare Metal users
# @param [Integer] id
# @return [Excon::Response]
def get_bare_metal_users(id)
response = Excon::Response.new
found = self.get_bare_metal_servers.body.map{|server| server['id']}.include?(id)
unless found
response.status = 404
response.body = {
"error" => "Unable to find object with id of '#{id}'.",
"code" => "SoftLayer_Exception_ObjectNotFound"
}
else
response.status = 200
response.body = get_users
end
response
end
end
class Real
def get_bare_metal_users(id)
request(:hardware_server, "#{id}/getUsers")
end
end
end
end
end
module Fog
module Softlayer
class Compute
class Mock
def get_users
[
{
"accountId"=>000000,
"address1"=>"Your address",
"authenticationToken"=>
{
"hash"=>"06e849qqq25e5266753043484893344232",
"user"=>nil,
"userId"=>000000
},
"city"=>"Your City",
"companyName"=>"Your Company",
"country"=>"Your country",
"createDate"=>"2014-03-05T13:23:04-06:00",
"daylightSavingsTimeFlag"=>true,
"denyAllResourceAccessOnCreateFlag"=>false,
"displayName"=>"Your name",
"email"=>"[email protected]",
"firstName"=>"Your name",
"forumPasswordHash"=>"121kdsksdkvm323j4j3",
"id"=>000000,
"lastName"=>"Your last name",
"localeId"=>1,
"modifyDate"=>"2014-03-05T13:23:04-06:00",
"officePhone"=>"+55 00 111-111",
"parentId"=>nil,
"passwordExpireDate"=>nil,
"permissionSystemVersion"=>2,
"postalCode"=>"000000-000",
"pptpVpnAllowedFlag"=>false,
"savedId"=>"000000",
"secondaryLoginManagementFlag"=>nil,
"secondaryLoginRequiredFlag"=>nil,
"secondaryPasswordModifyDate"=>"2014-03-05T13:40:12-06:00",
"secondaryPasswordTimeoutDays"=>nil,
"sslVpnAllowedFlag"=>false,
"state"=>"OT",
"statusDate"=>"2014-03-05T13:23:04-06:00",
"timezoneId"=>114,
"userStatusId"=>1001,
"username"=>"Your username",
"vpnManualConfig"=>false,
"account"=>
{
"accountManagedResourcesFlag"=>false,
"accountStatusId"=>1001,
"address1"=>"Your address 1",
"address2"=>"Your address 2",
"allowedPptpVpnQuantity"=>1,
"brandId"=>2,
"city"=>"Your city",
"claimedTaxExemptTxFlag"=>false,
"companyName"=>"Your company",
"country"=>"Your country",
"createDate"=>"2014-03-05T13:23:04-06:00",
"email"=>"[email protected]",
"firstName"=>"Your name",
"id"=>000000,
"isReseller"=>1,
"lastName"=>"Your last name",
"lateFeeProtectionFlag"=>nil,
"modifyDate"=>"2014-04-29T15:22:55-05:00",
"officePhone"=>"+00 00 0000-0000",
"postalCode"=>"00000-000",
"state"=>"OT",
"statusDate"=>nil,
"masterUser"=>nil
},
"apiAuthenticationKeys"=>
[
{
"authenticationKey"=>"43k43dsmkf9994m3mdkm3k2mcdsk32",
"id"=>000000,
"timestampKey"=>302399304309,
"userId"=>000000
}
],
"locale"=>
{
"friendlyName"=>"English",
"id"=>1,
"languageTag"=>"en-US",
"name"=>"English"
},
"timezone"=>
{
"id"=>114,
"longName"=>"(GMT-06:00) America/Dallas - CST", "name"=>"America/Chicago",
"offset"=>"-0600",
"shortName"=>"CST"
},
"userStatus"=>
{
"id"=>1001,
"keyName"=>"ACTIVE",
"name"=>"Active"
}
}
]
end
end
end
end
end
| 32.362416 | 90 | 0.454168 |
e8f19c7b55fc463186b3c6f65051cf61fe5232f0 | 1,169 | # encoding: utf-8
require 'spec_helper'
describe "SMTP Delivery Method" do
before(:each) do
Mail.defaults do
smtp = Net::SMTP.start('127.0.0.1', 25)
delivery_method :smtp_connection, :connection => smtp
end
end
after(:each) do
Mail.delivery_method.smtp.finish
end
it "should send an email using open SMTP connection" do
mail = Mail.deliver do
from '[email protected]'
to '[email protected], [email protected]'
subject 'invalid RFC2822'
end
MockSMTP.deliveries[0][0].should eq mail.encoded
MockSMTP.deliveries[0][1].should eq mail.from[0]
MockSMTP.deliveries[0][2].should eq mail.destinations
end
it "should be able to return actual SMTP protocol response" do
Mail.defaults do
smtp = Net::SMTP.start('127.0.0.1', 25)
delivery_method :smtp_connection, :connection => smtp, :port => 587, :return_response => true
end
mail = Mail.deliver do
from '[email protected]'
to '[email protected]'
subject 'invalid RFC2822'
end
response = mail.deliver!
response.should eq 'OK'
end
end
| 24.354167 | 99 | 0.643285 |
4a635bb5a7231013ecb3a12a3694d8b4c453bc10 | 179 | json.source_id @contact_inbox.source_id
json.pubsub_token @contact_inbox.pubsub_token
json.partial! 'public/api/v1/models/contact.json.jbuilder', resource: @contact_inbox.contact
| 44.75 | 92 | 0.843575 |
aba3dce4ba80a36c59f3aa11ea6032740e5a3ced | 4,483 | require 'test_helper'
# Tests the ActsAsAuthentic::EmailToken::Confirmation module.
class Confirmation < Minitest::Test
def test_confirm_email
Authlogic::Random.expects(:friendly_token).returns('IMvEDB6NJIm5Z7cSe2a')
o = Confirmable.new email: '[email protected]', new_email: '[email protected]'
t = Time.now
Timecop.freeze(t) do
o.confirm_email
assert_equal '[email protected]', o.email
assert_nil o.read_attribute(:new_email)
assert_equal 'IMvEDB6NJIm5Z7cSe2a', o.email_token
assert_equal t, o.email_token_updated_at
assert o.new_record?
end
end
def test_confirm_email_bang
Authlogic::Random.expects(:friendly_token).returns('IMvEDB6NJIm5Z7cSe2a')
o = Confirmable.new email: '[email protected]', new_email: '[email protected]'
t = Time.now
Timecop.freeze(t) do
o.confirm_email!
assert_equal '[email protected]', o.email
assert_nil o.read_attribute(:new_email)
assert_equal 'IMvEDB6NJIm5Z7cSe2a', o.email_token
assert_equal t, o.email_token_updated_at
assert o.persisted?
o.reload
assert_equal '[email protected]', o.email
assert_nil o.read_attribute(:new_email)
assert_equal 'IMvEDB6NJIm5Z7cSe2a', o.email_token
assert_equal t.to_i, o.email_token_updated_at.to_i
end
end
def test_confirm_email_activates
o = Activatable.new
o.confirm_email
assert o.activated
assert o.new_record?
end
def test_confirm_email_bang_activates
o = Activatable.create! email: '[email protected]'
o.confirm_email!
assert o.activated
assert o.persisted?
o.reload
assert o.activated
end
def test_custom_activation_method
o = CustomMailerClassAndMethod
end
def test_send_email_confirmation_when_changing_address
o = Confirmable.create! email: '[email protected]', new_email: nil
o.update_attributes! new_email: '[email protected]'
c = mock # The mailer requires a controller.
m = mock # The mailer will return this mock message.
m.expects(:deliver_now)
UserMailer.expects(:email_confirmation).with(o, c).returns(m)
assert o.maybe_deliver_email_confirmation!(c)
end
def test_custom_mailer_class_and_method
o = CustomMailerClassAndMethod.create! email: '[email protected]', new_email: nil
o.update_attributes! new_email: '[email protected]'
c = mock # The mailer requires a controller.
m = mock # The mailer will return this mock message.
m.expects(:deliver_now)
CustomUserMailer.expects(:custom_method).with(o, c).returns(m)
assert o.maybe_deliver_email_confirmation!(c)
end
def test_email_changed_previously_returns_false_for_clean_record
o = Confirmable.create! email: '[email protected]'
o.reload
refute o.email_changed_previously?
end
def test_email_changed_previously_returns_false_for_clean_record_with_new_email_set_to_same_value
o = Confirmable.create! email: '[email protected]'
o.update_attributes! new_email: '[email protected]'
o.reload
refute o.email_changed_previously?
end
def test_email_changed_previously_returns_true_when_email_changed
o = Confirmable.create! email: '[email protected]'
o.reload
o.update_attributes! email: '[email protected]'
assert o.email_changed_previously?
end
def test_email_changed_previously_returns_false_when_email_set_to_same_value
o = Confirmable.create! email: '[email protected]'
o.reload
o.update_attributes! email: '[email protected]'
refute o.email_changed_previously?
end
def test_email_changed_previously_returns_true_when_new_email_changed
o = Confirmable.create! email: '[email protected]'
o.reload
o.update_attributes! new_email: '[email protected]'
assert o.email_changed_previously?
end
def test_email_changed_previously_returns_false_when_new_email_set_to_same_value
o = Confirmable.create! email: '[email protected]', new_email: '[email protected]'
o.reload
o.update_attributes! new_email: '[email protected]'
refute o.email_changed_previously?
end
def test_new_email_defaults_to_current_email
o = Confirmable.new email: '[email protected]'
assert_equal '[email protected]', o.new_email
assert_equal '[email protected]', o.new_email_before_type_cast
end
def test_new_email_not_set_if_equal_to_current_email
o = Confirmable.new email: '[email protected]'
o.new_email = '[email protected]'
assert_nil o.read_attribute(:new_email)
o.save
o.reload
assert_nil o.read_attribute(:new_email)
end
end | 33.706767 | 99 | 0.740576 |
f82b9c2e5cbd13c65fb130aee4176a79b2032a54 | 2,887 | # encoding: UTF-8
# This file is auto-generated from the current state of the database. Instead
# of editing this file, please use the migrations feature of Active Record to
# incrementally modify your database, and then regenerate this schema definition.
#
# Note that this schema.rb definition is the authoritative source for your
# database schema. If you need to create the application database on another
# system, you should be using db:schema:load, not running all the migrations
# from scratch. The latter is a flawed and unsustainable approach (the more migrations
# you'll amass, the slower it'll run and the greater likelihood for issues).
#
# It's strongly recommended that you check this file into your version control system.
ActiveRecord::Schema.define(version: 20160801222837) do
create_table "boxes", force: :cascade do |t|
t.string "subscription"
t.string "title"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.string "theme_title"
t.datetime "starts_at"
t.integer "plan_id"
t.boolean "shipped", default: false
end
create_table "items", force: :cascade do |t|
t.string "title"
t.string "description"
t.string "image"
t.string "size"
t.string "url"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.integer "price"
t.integer "box_id"
t.string "image_file_name"
t.string "image_content_type"
t.integer "image_file_size"
t.datetime "image_updated_at"
end
create_table "plans", force: :cascade do |t|
t.string "name"
t.decimal "price"
t.boolean "active", default: false, null: false
t.integer "user_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.text "description"
end
add_index "plans", ["user_id"], name: "index_plans_on_user_id"
create_table "registrations", force: :cascade do |t|
t.integer "plan_id"
t.integer "user_id"
t.datetime "created_at"
t.datetime "updated_at"
t.datetime "expired_at"
end
create_table "users", force: :cascade do |t|
t.string "email"
t.string "first_name"
t.string "last_name"
t.string "password_digest"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.boolean "admin", default: false
t.string "provider"
t.string "oauth_token"
t.datetime "oauth_expires_at"
t.text "uid"
t.string "reset_digest"
t.datetime "reset_sent_at"
t.string "avatar_file_name"
t.string "avatar_content_type"
t.integer "avatar_file_size"
t.datetime "avatar_updated_at"
t.string "stripe_token"
end
end
| 33.964706 | 86 | 0.650156 |
f839144cd1d8fdb53878c838ab3b955fb6218dd2 | 1,353 | class CargoLlvmLines < Formula
desc "Count lines of LLVM IR per generic function"
homepage "https://github.com/dtolnay/cargo-llvm-lines"
url "https://github.com/dtolnay/cargo-llvm-lines/archive/0.4.11.tar.gz"
sha256 "7bdbabf728b47e6312376bce694429ba397a3c991a8ee1cbf28179442980cca1"
license any_of: ["Apache-2.0", "MIT"]
head "https://github.com/dtolnay/cargo-llvm-lines.git", branch: "master"
bottle do
sha256 cellar: :any_skip_relocation, arm64_big_sur: "2012ba146865a090dc70c62ffcc0dae32d32f9607ac0287fc59fbb704e6bc2e1"
sha256 cellar: :any_skip_relocation, big_sur: "7c7bcd775252bb1725b1ecce04d39765daa9eb757ec22517c5471cb2d8c43e8b"
sha256 cellar: :any_skip_relocation, catalina: "cf663596ab5fcac259f1fef1f4f194ac85ad4b081fb50c599889b66a6cde145d"
sha256 cellar: :any_skip_relocation, mojave: "280deac6629170aa055343f722d51d5d0b5114c8222e8fd32e4bdebe8f5b140b"
sha256 cellar: :any_skip_relocation, x86_64_linux: "d4a1b487955d0139aa7b8952bec9641ebe49825a99b8b093b98465cf475b220f"
end
depends_on "rust"
def install
system "cargo", "install", *std_cargo_args
end
test do
system "cargo", "new", "hello_world", "--bin"
cd "hello_world" do
output = shell_output("cargo llvm-lines 2>&1")
assert_match "core::ops::function::FnOnce::call_once", output
end
end
end
| 43.645161 | 122 | 0.77014 |
617c90c190c722a555d481974ccbcc23df7b7ea0 | 3,914 | # 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_04_084430) do
# These are extensions that must be enabled in order to support this database
enable_extension "plpgsql"
create_table "active_storage_attachments", force: :cascade do |t|
t.string "name", null: false
t.string "record_type", null: false
t.bigint "record_id", null: false
t.bigint "blob_id", null: false
t.datetime "created_at", null: false
t.index ["blob_id"], name: "index_active_storage_attachments_on_blob_id"
t.index ["record_type", "record_id", "name", "blob_id"], name: "index_active_storage_attachments_uniqueness", unique: true
end
create_table "active_storage_blobs", force: :cascade do |t|
t.string "key", null: false
t.string "filename", null: false
t.string "content_type"
t.text "metadata"
t.bigint "byte_size", null: false
t.string "checksum", null: false
t.datetime "created_at", null: false
t.index ["key"], name: "index_active_storage_blobs_on_key", unique: true
end
create_table "comments", force: :cascade do |t|
t.text "content"
t.bigint "user_id"
t.bigint "gambit_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.index ["gambit_id"], name: "index_comments_on_gambit_id"
t.index ["user_id"], name: "index_comments_on_user_id"
end
create_table "followings", force: :cascade do |t|
t.bigint "follower_id"
t.bigint "followed_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.index ["followed_id"], name: "index_followings_on_followed_id"
t.index ["follower_id"], name: "index_followings_on_follower_id"
end
create_table "gambits", force: :cascade do |t|
t.text "text"
t.bigint "user_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.index ["user_id"], name: "index_gambits_on_user_id"
end
create_table "likes", force: :cascade do |t|
t.bigint "user_id"
t.bigint "gambit_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.index ["gambit_id"], name: "index_likes_on_gambit_id"
t.index ["user_id"], name: "index_likes_on_user_id"
end
create_table "users", force: :cascade do |t|
t.string "email", default: "", null: false
t.string "encrypted_password", default: "", null: false
t.string "reset_password_token"
t.datetime "reset_password_sent_at"
t.datetime "remember_created_at"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.string "username"
t.string "fullname"
t.index ["email"], name: "index_users_on_email", unique: true
t.index ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true
end
add_foreign_key "active_storage_attachments", "active_storage_blobs", column: "blob_id"
add_foreign_key "comments", "gambits"
add_foreign_key "comments", "users"
add_foreign_key "followings", "users", column: "followed_id"
add_foreign_key "followings", "users", column: "follower_id"
add_foreign_key "gambits", "users"
add_foreign_key "likes", "gambits"
add_foreign_key "likes", "users"
end
| 39.938776 | 126 | 0.721513 |
ff2bd7aefdf1c434a6a7a2554905efc027aabcca | 913 | module API
module V1
class Auth < Grape::API
include API::V1::Defaults
resource :auth do
desc "Creates and returns access_token if valid login"
params do
requires :username, type: String, desc: "Username or email address"
requires :password, type: String, desc: "Password"
end
post :login do
user = User.find_by(username: params[:username])
if user && user.authenticate(params[:password])
key = ApiKey.create(user_id: user.id)
{token: key.access_token}
else
error!('Unauthorized.', 401)
end
end
desc "Returns pong if logged in correctly"
params do
requires :token, type: String, desc: "Access token."
end
get :ping do
authenticate!
{ message: "pong" }
end
end
end
end
end
| 26.085714 | 77 | 0.554217 |
ff0e04b0862254c3dda7ddffd8a306f74ca9e48f | 2,602 | class EntriesController < ApplicationController
get '/entries' do
if logged_in?
@entries = current_user.entries
# @user = User.find_by(email: params[:email])
erb :'entries/entries'
else
# If a user is not logged in, it will redirect to /login.
redirect '/login'
end
end
post '/entries' do
if logged_in?
if params[:content] == "" || params[:title] == ""
# raise error, hey you can't leave it blank
redirect to '/entries'
else
@entry = Entry.create(title: params[:title], content: params[:content], user_id: @user.id)
@entry.save
redirect to "/entries/#{@entry.id}"
end
else
redirect '/login'
end
end
get '/entries/:id' do
if logged_in?
@entry = Entry.find_by(id: params[:id])
erb :'entries/show'
else
redirect '/login'
end
end
get '/entries/:id/edit' do
if logged_in?
@entry = Entry.find_by(id: params[:id])
if @entry && @entry.user_id == current_user.id
erb :'entries/edit'
else
redirect '/entries'
end
else
redirect '/login'
end
end
patch '/entries/:id' do
if logged_in?
if params[:content] == "" || params[:title] == ""
redirect to "/entries/#{params[:id]}/edit"
else
@entry = Entry.find_by_id(params[:id])
if @entry && @entry.user_id == current_user.id
# binding.pry
@entry.update(title: params[:title],content: params[:content])
redirect to "/entries/#{@entry.id}"
else
redirect '/entries/:id'
end
end
end
end
# delete '/entries/:id' do
# @entry = Entry.find_by(username: params[:username])
# if logged_in?
# @entry = Entry.find_by(id: params[:id])
# if @entry && @entry.user_id == @user.id
# @entry.destroy
# @entry.delete
# end
# redirect '/entries'
# else
# redirect '/index'
# end
# end
delete '/entries/:id' do
@entry = Entry.find_by(id: params[:id])
@entry.destroy
@entry.delete
redirect '/entries'
end
end | 29.235955 | 106 | 0.461184 |
4a3a7e969202ad606f98bda38a54191a4cb110a8 | 413 | # frozen_string_literal: true
module OrangeData
class ReceiptStatus
def initialize(id:, inn: nil, config: OrangeData.configuration)
@config = config
@id = id
@inn = inn || @config.inn
end
def sync!
Client.request(payload, api_name: :get_receipt_status)
end
private
def payload
@payload ||= {
id: @id,
inn: @inn
}
end
end
end
| 16.52 | 67 | 0.585956 |
873391eca80aba4e0156117ce7b0b61b7704c0aa | 137 | class MakeUserEmailsUnique < ActiveRecord::Migration[6.0]
def change
change_column :users, :email, :string, unique: true
end
end
| 22.833333 | 57 | 0.744526 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.