text stringlengths 10 2.61M |
|---|
class UsersController < ApplicationController
before_filter :admin_check, :only => [:admin]
def index
@users = User.all
end
def admin
# admin should be able to delete and change everything.
@users = User.all
@songs = Song.all
@bands = Band.all
end
def show
@user = User.find_by_name(params[:id])
end
private
def admin_check
# send back to index except user is admin and logged in
unless current_user.try("admin?")
flash[:alert] = "Hey"
redirect_to root_path
end
end
end
|
class CreateTagWizardQuestions < ActiveRecord::Migration
def self.up
create_table :tag_wizard_questions do |t|
t.column :asking_text, :string
t.column :active, :boolean
t.column :position, :int
end
end
def self.down
drop_table :tag_wizard_questions
end
end
|
FactoryBot.define do
factory :user do
last_name {"武雄"}
first_name {"フリマ"}
last_name_kana {"タケオ"}
first_name_kana {"フリマ"}
nickname {"フリマ武雄"}
birthday {Faker::Date.birthday(min_age: 18, max_age: 65)}
password {"test002"}
password_confirmation {password}
email {Faker::Internet.free_email}
end
end
|
require 'eventmachine'
module Messenger
class WebsocketApi
def initialize(host, session)
@session = session
@host = host
@thread = Thread.new do
EM.run do
@client = Faye::Client.new(@host)
@client.add_extension WebsocketAuth.new(@session)
end
end
end
def subscribe(channel, &block)
@client.subscribe channel, &block
end
def unsubscribe(channel, &block)
@client.unsubscribe channel, &block
end
def run
@thread.run
end
def exit
@thread.exit
end
class WebsocketAuth
def initialize(tokens)
@session = tokens
end
def outgoing(message, callback)
message['ext'] = @session.session
callback.call(message)
end
end
end
end |
class CreatePartners < ActiveRecord::Migration
def self.up
create_table :partners do |t|
t.references :title
t.string :first_name
t.string :middle_names
t.string :last_name
t.string :email
t.string :mobile_phone
t.string :home_phone
t.datetime :deleted_at
t.integer :account_id
t.integer :created_by
t.string :avatar_file_name
t.string :avatar_content_type
t.integer :avatar_file_size
t.datetime :avatar_updated_at
t.string :twitter
t.string :facebook
t.date :dob
t.references :gender
t.string :state
t.references :household
t.timestamps
end
add_index :partners, :account_id
end
def self.down
remove_index :partners, :account_id
drop_table :partners
end
end
|
require 'test_helper'
class ProductorsControllerTest < ActionDispatch::IntegrationTest
setup do
@productor = productors(:one)
end
test "should get index" do
get productors_url
assert_response :success
end
test "should get new" do
get new_productor_url
assert_response :success
end
test "should create productor" do
assert_difference('Productor.count') do
post productors_url, params: { productor: { country_id: @productor.country_id, name: @productor.name } }
end
assert_redirected_to productor_url(Productor.last)
end
test "should show productor" do
get productor_url(@productor)
assert_response :success
end
test "should get edit" do
get edit_productor_url(@productor)
assert_response :success
end
test "should update productor" do
patch productor_url(@productor), params: { productor: { country_id: @productor.country_id, name: @productor.name } }
assert_redirected_to productor_url(@productor)
end
test "should destroy productor" do
assert_difference('Productor.count', -1) do
delete productor_url(@productor)
end
assert_redirected_to productors_url
end
end
|
source 'https://rubygems.org'
ruby '2.0.0'
gem 'rails', '4.0.1'
gem 'sass-rails', '~> 4.0.0'
gem 'uglifier', '>= 1.3.0'
gem 'coffee-rails', '~> 4.0.0'
gem 'jquery-rails'
gem 'httparty'
# Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder
gem 'jbuilder', '~> 1.2'
gem 'carrierwave'
gem 'fog'
gem 'figaro'
gem 'mini_magick'
group :development do
gem 'better_errors'
gem 'binding_of_caller'
end
group :development, :test do
gem 'rspec-rails'
gem 'guard-rspec', require: false
gem 'factory_girl_rails'
gem 'selenium-webdriver', '2.35.1'
gem 'capybara', '2.1.0' # Capybara is an integration testing tool for rack based web applications. It simulates how a user would interact with a website
gem 'sqlite3'
gem 'simplecov' # Code coverage for Ruby 1.9+ with a powerful configuration library and automatic merging of coverage across test suites
gem 'rubocop' # Automatic Ruby code style checking tool. Aims to enforce the community-driven Ruby Style Guide
gem 'brakeman' # Brakeman detects security vulnerabilities in Ruby on Rails applications via static analysis
end
group :test do
gem "nyan-cat-formatter"
end
group :production do
gem 'pg'
gem 'rails_12factor'
end
group :doc do
gem 'sdoc', require: false
end
gem 'bcrypt-ruby', '~> 3.1.2'
|
class BackupJob < ActiveRecord::Base
attr_accessible :started_at, :finished_at, :state, :directory
mount_uploader :backup_file, BackupFileUploader
before_create :set_state_to_queued
after_create :initiate_backup
def to_s
self.started_at.to_s
end
def set_state_to_queued
self.state ||= 'queued'
self.started_at = Time.now
end
def initiate_backup
if self.state == 'force now'
self.state = 'queued'
self.make_a_backup
else
self.delay.make_a_backup
end
end
def make_a_backup
backup_directory = '/var/backups/GS5'
backup_name_prefix = 'GS5-backup-'
if self.finished_at.nil? && self.state == 'queued'
self.state = 'running'
self.save
original_directories = Dir.glob("#{backup_directory}/*")
system "backup perform --trigger GS5 --config_file #{Rails.root.join('config','backup.rb')}"
tmp_backup_directory = (Dir.glob("#{backup_directory}/*") - original_directories).first
if tmp_backup_directory.blank?
self.state = 'failed'
else
system "cd #{backup_directory} && nice -n 19 ionice -c2 -n7 sudo /bin/tar czf #{backup_name_prefix}#{File.basename(tmp_backup_directory)}.tar.gz #{File.basename(tmp_backup_directory)}"
require 'fileutils'
FileUtils.rm_rf tmp_backup_directory
file = File::Stat.new("#{backup_directory}/#{backup_name_prefix}#{File.basename(tmp_backup_directory)}.tar.gz")
self.directory = File.basename(tmp_backup_directory)
self.backup_file = File.open("#{backup_directory}/#{backup_name_prefix}#{File.basename(tmp_backup_directory)}.tar.gz")
self.finished_at = Time.now
self.state = 'successful'
end
self.save
end
end
end
|
feature 'view bookmarks' do
scenario 'see the list of bookmarks' do
visit '/bookmarks'
expect(page).to have_content "www.google.com"
end
end |
class CreateComments < ActiveRecord::Migration[6.0]
def change
create_table :comments do |t|
t.integer :user_id
t.integer :imageable_id
t.string :imageable_type
t.text :content
t.timestamps
end
add_index :comments, [:imageable_type, :imageable_id]
end
end
|
Puppet::Type.newtype(:f5_virtualserver) do
@doc = "Manages F5 virtualservers."
apply_to_device
ensurable do
defaultvalues
defaultto :present
end
newparam(:name, :namevar=>true) do
desc "The virtualserver name."
validate do |value|
unless Puppet::Util.absolute_path?(value)
fail Puppet::Error, "Virtualserver names must be a fully qualified path, not '#{value}'"
end
end
end
newproperty(:description) do
desc "The virtualserver description"
end
newproperty(:address) do
desc "The virtualserver address"
end
newproperty(:default_pool) do
desc "The virtualserver default pool"
end
newproperty(:port) do
desc "The virtualserver port"
munge do |value|
begin
Integer(value)
rescue
fail Puppet::Error, "Parameter 'port' must be a number, not '#{value}'"
end
end
end
newproperty(:fallback_persistence_profile) do
desc "The virtualserver fallback persistence profile"
end
newproperty(:persistence_profile) do
desc "The virtualserver default persistence profile"
end
newproperty(:protocol) do
desc "The virtualserver default persistence profile"
def should=(values)
super(values.upcase)
end
validate do |value|
valid_protocols =
["ANY", "IPV6", "ROUTING", "NONE", "FRAGMENT", "DSTOPTS", "TCP", "UDP", "ICMP", "ICMPV6",
"OSPF", "SCTP", "UNKNOWN"]
unless valid_protocols.include?(value.upcase)
fail Puppet::Error, "Parameter '#{self.name}' must be one of:"\
" #{valid_protocols.inspect}, not '#{value.upcase}'"
end
end
munge do |value|
value.upcase
end
end
newproperty(:source_address_translation) do
desc "The source address translation setting of the virtualserver"
validate do |value|
unless ['automap', 'none'].include?(value.downcase) ||
Puppet::Util.absolute_path?(value)
fail Puppet::Error, "'source_address_translation' must be 'automap',"\
" 'none' or a fully qualified path, not '#{value.downcase}'"
end
end
munge do |value|
value.upcase! if ['automap', 'none'].include?(value.downcase)
value
end
end
###########################################################################
# Profiles
###########################################################################
newproperty(:auth_profiles, :array_matching => :all) do
# def insync?(is)
# is == :absent && @should.empty? || is.sort == @should.sort
# end
def insync?(is)
is.sort == @should.sort
end
# Actually display an empty list.
def should_to_s(newvalue)
newvalue.inspect
end
validate do |value|
unless Puppet::Util.absolute_path?(value)
fail Puppet::Error, "Parameter 'auth_profiles' must be"\
" a fully qualified path, not '#{value}'"
end
end
end
newproperty(:ftp_profile) do
validate do |value|
unless Puppet::Util.absolute_path?(value)
fail Puppet::Error, "Parameter 'ftp_profile' must be"\
" a fully qualified path, not '#{value}'"
end
end
end
newproperty(:http_profile) do
validate do |value|
unless Puppet::Util.absolute_path?(value)
fail Puppet::Error, "Parameter 'http_profile' must be"\
" a fully qualified path, not '#{value}'"
end
end
end
newproperty(:oneconnect_profile) do
validate do |value|
unless Puppet::Util.absolute_path?(value)
fail Puppet::Error, "Parameter 'oneconnect_profile' must be"\
" a fully qualified path, not '#{value}'"
end
end
end
newproperty(:protocol_profile_client) do
validate do |value|
unless Puppet::Util.absolute_path?(value)
fail Puppet::Error, "Parameter 'protocol_profile_client' must be"\
" a fully qualified path, not '#{value}'"
end
end
end
newproperty(:protocol_profile_server) do
validate do |value|
unless Puppet::Util.absolute_path?(value)
fail Puppet::Error, "Parameter 'protocol_profile_server' must be"\
" a fully qualified path, not '#{value}'"
end
end
end
newproperty(:responseadapt_profile) do
validate do |value|
unless Puppet::Util.absolute_path?(value)
fail Puppet::Error, "Parameter 'responseadapt_profile' must be"\
" a fully qualified path, not '#{value}'"
end
end
end
newproperty(:requestadapt_profile) do
validate do |value|
unless Puppet::Util.absolute_path?(value)
fail Puppet::Error, "Parameter 'requestadapt_profile' must be"\
" a fully qualified path, not '#{value}'"
end
end
end
newproperty(:rules, :array_matching => :all) do
def insync?(is)
# Don't sort here because the order of rules matters,
# (we do sort on priority during prefetch)
is == @should
end
# Actually display an empty list.
def should_to_s(newvalue)
newvalue.inspect
end
validate do |value|
unless Puppet::Util.absolute_path?(value)
fail Puppet::Error, "Parameter 'rules' must be"\
" a fully qualified path, not '#{value}'"
end
end
end
newproperty(:sip_profile) do
validate do |value|
unless Puppet::Util.absolute_path?(value)
fail Puppet::Error, "Parameter 'sip_profile' must be"\
" a fully qualified path, not '#{value}'"
end
end
end
newproperty(:ssl_profiles_client, :array_matching => :all) do
# Override insync so it doesn't treat an empty list value
# as nil.
def insync?(is)
is.sort == @should.sort
end
# Actually display an empty list.
def should_to_s(newvalue)
newvalue.inspect
end
validate do |value|
unless Puppet::Util.absolute_path?(value)
fail Puppet::Error, "Parameter 'ssl_profile_server' must be"\
" a fully qualified path, not '#{value}'"
end
end
end
newproperty(:ssl_profiles_server, :array_matching => :all) do
def insync?(is)
is.sort == @should.sort
end
def should_to_s(newvalue)
newvalue.inspect
end
validate do |value|
unless Puppet::Util.absolute_path?(value)
fail Puppet::Error, "Parameter 'ssl_profile_server' must be"\
" a fully qualified path, not '#{value}'"
end
end
end
newproperty(:stream_profile) do
validate do |value|
unless Puppet::Util.absolute_path?(value)
fail Puppet::Error, "Parameter 'stream_profile' must be"\
" a fully qualified path, not '#{value}'"
end
end
end
newproperty(:statistics_profile) do
validate do |value|
unless Puppet::Util.absolute_path?(value)
fail Puppet::Error, "Parameter 'atcreate_statistics_profile' must be"\
" a fully qualified path, not '#{value}'"
end
end
end
newproperty(:xml_profile) do
validate do |value|
unless Puppet::Util.absolute_path?(value)
fail Puppet::Error, "Parameter 'xml_profile' must be"\
" a fully qualified path, not '#{value}'"
end
end
end
newproperty(:type) do
desc "The virtualserver type"
def should=(values)
super(values.upcase)
end
validate do |value|
valid_types =
["POOL", "IP_FORWARDING", "L2_FORWARDING", "REJECT", "FAST_L4", "FAST_HTTP", "STATELESS",
"DHCP_RELAY", "UNKNOWN", "INTERNAL"]
unless valid_types.include?(value)
fail Puppet::Error, "Parameter 'type' must be one of:"\
" #{valid_types.inspect}, not '#{value}'"
end
end
end
newproperty(:wildmask) do
desc "The virtualserver wildmask"
end
###########################################################################
# Parameters used at creation.
###########################################################################
# These attributes are parameters because, often, we want objects to be
# *created* with property values X, but still let a human make changes
# to them without puppet getting in the way.
newparam(:atcreate_description) do
desc "The virtualserver description at creation."
end
newparam(:atcreate_address) do
desc "The virtualserver address at creation."
end
newparam(:atcreate_default_pool) do
desc "The virtualserver default pool at creation."
defaultto "" # None
end
newparam(:atcreate_port) do
desc "The virtualserver port at creation."
munge do |value|
begin
Integer(value)
rescue
fail Puppet::Error, "Parameter 'atcreate_port' must be a number, not '#{value}'"
end
end
end
newparam(:atcreate_fallback_persistence_profile) do
desc "The virtualserver fallback persistence profile at creation."
end
newparam(:atcreate_persistence_profile) do
desc "The virtualserver default persistence profile at creation."
end
newparam(:atcreate_protocol) do
desc "The virtualserver default persistence profile at creation."
validate do |value|
valid_protocols =
["ANY", "IPV6", "ROUTING", "NONE", "FRAGMENT", "DSTOPTS", "TCP", "UDP", "ICMP", "ICMPV6",
"OSPF", "SCTP", "UNKNOWN"]
unless valid_protocols.include?(value)
fail Puppet::Error, "Parameter '#{self.name}' must be one of:"\
" #{valid_protocols.inspect}, not '#{value}'"
end
end
munge do |value|
value.upcase
end
defaultto "TCP"
end
newparam(:atcreate_auth_profiles) do
validate do |value|
value = [value] unless value.is_a?(Array)
value.each do |item|
unless Puppet::Util.absolute_path?(item)
fail Puppet::Error, "Parameter 'atcreate_auth_profiles' must be"\
" a fully qualified path, not '#{item}'"
end
end
end
munge do |value|
value.is_a?(Array) ? value : [value]
end
end
newparam(:atcreate_ftp_profile) do
validate do |value|
unless Puppet::Util.absolute_path?(value)
fail Puppet::Error, "Parameter 'atcreate_ftp_profile' must be"\
" a fully qualified path, not '#{value}'"
end
end
end
newparam(:atcreate_http_profile) do
validate do |value|
unless Puppet::Util.absolute_path?(value)
fail Puppet::Error, "Parameter 'atcreate_http_profile' must be"\
" a fully qualified path, not '#{value}'"
end
end
end
newparam(:atcreate_oneconnect_profile) do
validate do |value|
unless Puppet::Util.absolute_path?(value)
fail Puppet::Error, "Parameter 'atcreate_oneconnect_profile' must be"\
" a fully qualified path, not '#{value}'"
end
end
end
newparam(:atcreate_protocol_profile_client) do
validate do |value|
unless Puppet::Util.absolute_path?(value)
fail Puppet::Error, "Parameter 'atcreate_protocol_profile_client'"\
" must be a fully qualified path, not '#{value}'"
end
end
end
newparam(:atcreate_protocol_profile_server) do
validate do |value|
unless Puppet::Util.absolute_path?(value)
fail Puppet::Error, "Parameter 'atcreate_protocol_profile_server'"\
" must be a fully qualified path, not '#{value}'"
end
end
end
newparam(:atcreate_requestadapt_profile) do
validate do |value|
unless Puppet::Util.absolute_path?(value)
fail Puppet::Error, "Parameter 'atcreate_requestadapt_profile' must be"\
" a fully qualified path, not '#{value}'"
end
end
end
newparam(:atcreate_responseadapt_profile) do
validate do |value|
unless Puppet::Util.absolute_path?(value)
fail Puppet::Error, "Parameter 'atcreate_responseadapt_profile' must be"\
" a fully qualified path, not '#{value}'"
end
end
end
newparam(:atcreate_sip_profile) do
validate do |value|
unless Puppet::Util.absolute_path?(value)
fail Puppet::Error, "Parameter 'atcreate_sip_profile' must be"\
" a fully qualified path, not '#{value}'"
end
end
end
newparam(:atcreate_ssl_profiles_client) do
validate do |value|
value = [value] unless value.is_a?(Array)
value.each do |item|
unless Puppet::Util.absolute_path?(item)
fail Puppet::Error, "Parameter 'atcreate_ssl_profiles_client' must be"\
" a fully qualified path, not '#{item}'"
end
end
end
munge do |value|
value.is_a?(Array) ? value : [value]
end
end
newparam(:atcreate_ssl_profiles_server) do
validate do |value|
value = [value] unless value.is_a?(Array)
value.each do |item|
unless Puppet::Util.absolute_path?(item)
fail Puppet::Error, "Parameter 'atcreate_ssl_profiles_server' must be"\
" a fully qualified path, not '#{item}'"
end
end
end
munge do |value|
value.is_a?(Array) ? value : [value]
end
end
newparam(:atcreate_statistics_profile) do
validate do |value|
unless Puppet::Util.absolute_path?(value)
fail Puppet::Error, "Parameter 'atcreate_statistics_profile' must be"\
" a fully qualified path, not '#{value}'"
end
end
end
newparam(:atcreate_stream_profile) do
validate do |value|
unless Puppet::Util.absolute_path?(value)
fail Puppet::Error, "Parameter 'atcreate_stream_profile' must be"\
" a fully qualified path, not '#{value}'"
end
end
end
newparam(:atcreate_xml_profile) do
validate do |value|
unless Puppet::Util.absolute_path?(value)
fail Puppet::Error, "Parameter 'atcreate_xml_profile' must be"\
" a fully qualified path, not '#{value}'"
end
end
end
newparam(:atcreate_rules) do
validate do |value|
value = [value] unless value.is_a?(Array)
value.each do |item|
unless Puppet::Util.absolute_path?(item)
fail Puppet::Error, "Parameter 'atcreate_rules' must be"\
" a fully qualified path, not '#{item}'"
end
end
end
munge do |value|
value.is_a?(Array) ? value : [value]
end
end
newparam(:atcreate_source_address_translation) do
desc "The source address translation setting of the virtualserver"
validate do |value|
unless ['AUTOMAP', 'NONE'].include?(value.upcase) ||
Puppet::Util.absolute_path?(value)
fail Puppet::Error, "'atcreate_source_address_translation' must be"\
" 'automap', 'none' or a fully qualified path, not '#{value}'"
end
end
munge do |value|
value.upcase! if ['automap', 'none'].include?(value.downcase)
value
end
end
newparam(:atcreate_type) do
desc "The virtualserver type at creation."
validate do |value|
valid_types =
["POOL", "IP_FORWARDING", "L2_FORWARDING", "REJECT", "FAST_L4", "FAST_HTTP", "STATELESS",
"DHCP_RELAY", "UNKNOWN", "INTERNAL"]
unless valid_types.include?(value.upcase)
fail Puppet::Error, "Parameter 'type' must be one of:"\
" #{valid_types.inspect}, not '#{value.upcase}'"
end
end
munge do |value|
value.upcase
end
defaultto "POOL"
end
newparam(:atcreate_wildmask) do
desc "The virtualserver wildmask at creation."
defaultto "255.255.255.255"
end
###########################################################################
# Validation
###########################################################################
validate do
if self[:ensure] == :present
if self[:address].nil? && self[:atcreate_address].nil?
fail Puppet::Error, "Parameter 'address' must be defined"
end
if self[:port].nil? && self[:atcreate_port].nil?
fail Puppet::Error, "Parameter 'port' must be defined"
end
end
end
autorequire(:f5_partition) do
File.dirname(self[:name])
end
# TODO: Autorequire all profiles
autorequire(:f5_pool) do
if !(self[:default_pool].nil? || self[:default_pool].empty?)
self[:default_pool]
elsif !(self[:atcreate_default_pool].nil? || self[:atcreate_default_pool].empty?)
self[:atcreate_default_pool]
end
end
end
|
require 'authenticate/testing/controller_helpers'
require 'authenticate/testing/view_helpers'
RSpec.configure do |config|
config.include Authenticate::Testing::ControllerHelpers, type: :controller
config.include Authenticate::Testing::ViewHelpers, type: :view
config.before(:each, type: :view) do
view.extend Authenticate::Testing::ViewHelpers::CurrentUser
end
end
|
#!/usr/bin/env ruby
# A bubble sorting algorithm
# Accept an array and return a sorted array
# Extend Array class to call from array object
class Array
def bubble_sort
i = self.length - 1
while i > 0
(0..(i-1)).each do |j|
if self[j + 1] < self[j]
self[j],self[j+1] = self[j+1],self[j]
end
end
i -= 1
end
return self
end
def bubble_sort_by
i = self.length - 1
while i > 0
(0..(i-1)).each do |j|
a = self[j]
b = self[j + 1]
if yield(a,b) > 0
self[j],self[j+1] = self[j+1],self[j]
end
end
i -= 1
end
return self
end
end
test = [4,23,7,5,2,1]
puts test.bubble_sort
words = ['one', 'bigger', 'is']
puts words.bubble_sort_by {|a,b| a.length - b.length}
|
require 'factory_girl'
FactoryGirl.define do
factory :banner do
describe "A random description"
association :block, factory: :block
sequence(:position) { |n| Random.new.rand(80) }
photo Rack::Test::UploadedFile.new(Rails.root.join('spec/fixtures/issue.png'),
'image/png')
trait :with_url do
url "http://www.lamezor.com"
end
end
end |
class AddObsToMaintasks < ActiveRecord::Migration
def change
add_column :maintasks, :obs, :string
end
end
|
require 'rails_helper'
describe TestA do
let(:a) { TestA.create }
let(:bs) {
[
TestB.create(test_a: a),
TestB.create(test_a: a),
TestB.create(test_a: a),
TestB.create(test_a: a),
TestB.create(test_a: a),
]
}
before do
a.update(singular_b: bs.last)
end
describe 'eager_load the parameters' do
it 'has all 5 test_bs loaded and represented in properties correctly' do
t = TestA.eager_load(:test_bs, :singular_b).first
expect(t.singular_b).to eq(bs.last)
expect(t.test_bs).to match_array(bs)
end
end
end
|
class UsersController < ApplicationController
before_filter :authenticate_user!, :except => [ :new, :create ]
def new
@user = User.new
end
def create
@user = User.new(user_params)
@secrate_code = SecrateCode.find_by_id(params[:secrate_code][:secrate_code])
if @user.valid? && @user.save
@secrate_code.update_attributes(:user_id => @user.id)
sign_in(@user)
redirect_to root_path
else
render :action => 'new'
end
end
def show
end
def user_params
params.require(:user).permit(:first,
:last, :email, :password, :password_confirmation)
end
end
|
class Host < ActiveRecord::Base
has_many :bookings
has_many :restaurants, through: :bookings
#has_one :booking
#belongs_to :waiter, through: :booking
#Find the current booking belonging to a host instance
#A host can only have one current booking at a time
def my_current_booking
Booking.all.find(self.id)
end
#The instance method pay_service will take an interger, convert it into a decimal
#Update the service_charge attribute for the booking instance for this host
def pay_service(number)
percentage = num / 100.0
current=self.my_current_booking
#update the booking with the percentage for service charge
current.update(service_charge: percentage)
end
end
|
require 'leankitkanban'
require 'kanban/card'
require 'active_support/core_ext/numeric/time'
module Kanban
class Api
def self.all(options = {})
cards_by(options) {|lane, card| true }
end
def self.done_cards(options = {})
cards_by(options) {|lane, card| ['Done', 'Ready to Release'].include?(lane['Title']) }
end
def self.cards_missing_size(options = {})
cards_by(options) {|lane, card| [nil, 0].include?(card['Size']) }
end
def self.cards_missing_tags(options = {})
cards_by(options) {|lane, card| lane['Title'] != 'Saddle up' && [nil, ''].include?(card['Tags']) }
end
def self.cards_by(options = {})
cards = []
board = get_board(options)
board['Lanes'].each do |lane|
lane['Cards'].each do |card|
yield_val = yield(lane, card) if block_given?
cards << { :card => card, :lane => lane } if yield_val
end
end
cards.map {|card| Card.new(card[:card].merge('Lane' => card[:lane]['Title'])) }
end
def self.get_board(options = {})
opts = { :force_refresh => false }.merge(options)
if (opts[:force_refresh] || @board_refreshed_at.nil? || !@board_refreshed_at.between?(10.minutes.ago, 0.minutes.ago))
@board = LeanKitKanban::Board.find(46341228).first
@board_refreshed_at = Time.now
end
@board
end
end
end
|
# ブロックを使い配列のメソッド
## map/collect
## select/find_all/reject
## find/detect
## inject/reduce
### mapメソッドは、要素の数だけ繰り返しブロックを実行し、ブロックの戻り値を集めた配列を作成して返す
numbers = [1,2,3,4,5,6]
new_numbers = numbers.map{|n| n*10}
puts new_numbers #⇛[10,20,30,40,50,60]
### selectメソッドは、条件に合う要素を探して集めます。
numbers = [1,2,3,4,5]
#ブロックの戻り値が真になった要素だけが集められる
even_numbers = numbers.select{|n| n.even?}
puts even_numbers #⇛[2,4]
### rejectメソッドはselectメソッドの逆。真になった要素を除外して新たな配列が生成される。
numbers = [1,2,3,4,5]
#ブロックの戻り値が真になった要素だけが除かれる
even_numbers = numbers.reject{|n| n.even?}
puts even_numbers #⇛[1,3,5]
### findメソッドはブロックの戻り値が真になって要素のうち最初の要素を取得
numbers = [1,2,3,4,5]
#ブロックの戻り値が真になった要素の最初の要素だけが取得される
even_numbers = numbers.find{|n| n.even?}
puts even_numbers #⇛[2]
### injectメソッドはブロックを使って繰り返し計算を行うのに使用。いまいち分かりづらいので、実際のコードを交えて説明。
numbers = [1,2,3,4]
sum = 0
numbers.each{|n| sum+=n}
puts sum #⇛10
### 上記のコードはinjectを使うと以下のようになる
numbers = [1,2,3,4]
sum = numbers.inject(0){|result,n| result + n}
puts sum #⇛10
### 何が行われているかというと
### ブロックの第一引数resultには初回のみinjectの引数(0)が代入される。
### 2回目以降はブロックの戻り値が入る。
### ブロックの第二引数nにはnumbersの要素が順番に入る。
### 1回目:result = 0, n=1, result(0)+n(1)=1, 次のresultには1が入る
### 2回目: result = 1, n=2, result(1)+n(2)=3 次のresultには3が入るといった形で繰り返す。
### numbers全ての要素に対してブロック内の処理が終わったら、injectメソッドの戻り値となる。
## &とシンボル(:)を使って簡潔に書く
['ruby','java','html',].map{|s| s.upcase}
#⇛["RUBY", "JAVA", "HTML"]
### 上記のコードは以下のように書ける
['ruby','java','html',].map(&:upcase)
### ブロックを渡す代わりに、(&:メソッド名)という引数を渡している
### これは①ブロック引数が1個だけである、②ブロックの中で呼び出すメソッドには引数が無い、③ブロックの中ではブロック引数に対してメソッドを1回呼び出す以外の処理がないという条件が揃っている時に使える
### 以下の状態では使えない
[1,2,3,4,5].select{|n| n%3 == 0}
#ブロックの中でメソッドではなく演算子を使っている
[9,10,11,12].map{|n| n.to_s(16)}
#ブロック無いのメソッドで引数を渡している
[1,2,3,4,5].map do |n|
m = n + 4
m.to_s
end
#ブロック内で複数の文を実行している
|
class Article < ActiveRecord::Base
class << self
def search(search_word)
Article.where("content like ?", "%" + search_word + "%")
end
end
end
|
module Api
module V1
class RoundSerializer < ::BaseSerializer
attributes :id, :sequential_number
has_many :games, serializer: GameSerializer
end
end
end
|
require File.expand_path('../../../../../easy_extensions/test/spec/spec_helper', __FILE__)
feature 'Easy Agile Board' do
before(:each) do
@user = FactoryGirl.create(:admin_user)
logged_user(@user)
end
let(:project) { FactoryGirl.create(:project, number_of_members: 3, number_of_issues: 0) }
let(:issues) { FactoryGirl.create_list(:issue, 5, project: project, assigned_to: nil) }
let(:sprints) { FactoryGirl.create_list(:easy_sprint, 3, project: project) }
scenario "display button on project page" do
visit project_path(project)
page.should have_css('a.button-1', text: 'Agile board')
end
scenario "display project team and project backlog" do
issues
visit easy_agile_board_path(project)
page.should have_css('h3', text: 'Project team')
project.users.each do |u|
page.should have_css('.project-team .member', text: u.name)
end
issues.each do |i|
page.should have_css('.project-backlog li', text: i.to_s)
end
end
scenario "display existing sprints", js: true do
sprints
visit easy_agile_board_path(project)
page.should have_css('div.easy-sprint', count: 3)
end
scenario "create new sprint", js: true do
visit easy_agile_board_path(project)
page.should have_css('.agile-board-body form.easy-sprint', count: 1)
click_button 'Create sprint'
page.should have_css('#errorExplanation', text: "Name can't be blank")
fill_in 'easy_sprint_name', with: 'Some new sprint'
click_button 'Create sprint'
page.should have_css('div.easy-sprint > h3', text: 'Some new sprint')
end
scenario "drag issue from project backlog to sprint backlog", js: true do
issues; sprints;
visit easy_agile_board_path(project)
issue = page.find('.project-backlog li:first-child')
issue_text = issue.text
sprint_backlog = page.find('.easy-sprint:nth-child(2) .agile-list.backlog')
issue.drag_to(sprint_backlog)
visit current_path
page.should have_css('.easy-sprint:nth-child(2) .agile-list.backlog li', count: 1, text: issue_text)
end
scenario "drag and drop issue assignment", js: true do
issues; sprints;
user = project.users.first
issue = issues.last
IssueEasySprintRelation.create(issue: issue, easy_sprint: sprints.last, relation_type: :backlog)
visit easy_agile_board_path(project)
page.find('h3', text: 'Project team').click
sleep 2
member_item = page.find(".project-team .member", text: user.name)
issue_item = page.find(".agile-issue-item", text: issue.subject)
member_item.drag_to(issue_item)
issue_item.should have_css("img[alt=\"#{user.name}\"]")
visit current_path
page.should have_css(".agile-issue-item img[alt=\"#{user.name}\"]")
end
end
|
class PietsController < ApplicationController
def index
@piets = Piet.all
end
def show
@piet = Piet.find(params[:id])
end
def new
@piet = Piet.new
end
def create
piet_params= params.require(:piet).permit( :name, :age, :gender, :theme, :image_url, :sint_id)
@piet = Piet.new(piet_params)
if @piet.save
redirect_to @piet
else
render 'new'
end
end
end
|
class AddReviewersCountToReviews < ActiveRecord::Migration
def change
add_column :reviews, :reviewers_count, :integer, default: 0
Review.reset_column_information
Review.with_deleted.find_each do |review|
Review.unscoped.reset_counters(review.id, :reviewers)
end
end
end
|
# frozen_string_literal: true
require 'rails_helper'
RSpec.describe Client, type: :model do
it 'has a valid factory' do
expect(FactoryBot.build(:client)).to be_valid
end
it 'does not contain invalid branch_id' do
expect(FactoryBot.build(:client, branch_id: 'q23jJ')).to be_invalid
end
it 'is invalid to nil branch_id' do
expect(FactoryBot.build(:client, branch_id: nil)).to be_invalid
end
it 'can not have blank branch_id' do
expect(FactoryBot.build(:client, branch_id: '')).to be_invalid
end
it 'can only have integer branch_id' do
expect(FactoryBot.build(:client, branch_id: '1.4')).to be_invalid
end
it 'is invalid to nil name' do
expect(FactoryBot.build(:client, name: nil)).to be_invalid
end
it 'is invalid to nil age' do
expect(FactoryBot.build(:client, age: nil)).to be_invalid
end
it 'only has integer age' do
expect(FactoryBot.build(:client, age: 'twenty')).to be_invalid
end
it 'only have 2 digit age' do
expect(FactoryBot.build(:client, age: '100')).to be_invalid
end
it 'is invalid to nil number' do
expect(FactoryBot.build(:client, number: nil)).to be_invalid
end
it 'can not have number digits>10' do
expect(FactoryBot.build(:client, number: '12345678913')).to be_invalid
end
it 'takes only integer number' do
expect(FactoryBot.build(:client, number: '123.55')).to be_invalid
end
it 'can not have blank number' do
expect(FactoryBot.build(:client, number: '')).to be_invalid
end
it 'has only valid email' do
expect(FactoryBot.build(:client, email: '123')).to be_invalid
end
it 'has only valid email' do
expect(FactoryBot.build(:client, email: 'zaman@')).to be_invalid
end
it 'has a valid email' do
expect(FactoryBot.build(:client, email: 'test@gmail.com')).to be_valid
end
it 'allows email as nil' do
expect(FactoryBot.build(:client, email: nil)).to be_valid
end
it 'can not have pan less than 10 char' do
expect(FactoryBot.build(:client, pan: '123fa')).to be_invalid
end
it 'can only have 10 char pan' do
expect(FactoryBot.build(:client, pan: '123456lajsdf')).to be_invalid
end
it 'has a valid pan' do
expect(FactoryBot.build(:client, pan: 'ABCDE12342')).to be_valid
end
end
|
class ApplicationController < ActionController::Base
protect_from_forgery
protected
#checks to see if user is logged in
def confirm_logged_in
unless session[:email]
flash[:error] = "Please log in or register."
redirect_to(:controller => 'access', :action => 'index')
return false #halts the before_filter
else
return true
end
end
#checks to see if user is an editor
def confirm_editor
if session[:user_id]!=nil
@user=User.find(session[:user_id])
if !@user.editor
#flash[:error] = "Please log in or register."
redirect_to(:controller => 'access', :action => 'index')
return false #halts the before_filter
else
return true
end
else
redirect_to(:controller => 'access', :action => 'index')
end
end
private
#if user is logged in, create @user variable
def current_user
@user||=User.find(session[:user_id]) if session[:user_id]
end
helper_method :current_user
end
|
require 'net/http'
require 'uri'
require 'json'
module GithubGraphql
GITHUB_URI = URI("https://api.github.com/graphql")
GITHUB_ACCESS_TOKEN = ENV['GITHUB_ACCESS_TOKEN']
def self.query(query, variables = nil)
req = Net::HTTP::Post.new(
GITHUB_URI,
"Content-Type" => "application/json",
"Authorization" => "Bearer #{GITHUB_ACCESS_TOKEN}",
"Accept" => "application/vnd.github.shadow-cat-preview+json", # for isDraft
)
if !variables.nil?
req.body = {query: query, variables: variables}.to_json
else
req.body = {query: query}.to_json
end
res = Net::HTTP.start(
GITHUB_URI.hostname, GITHUB_URI.port, :use_ssl => true
) { |http| http.request(req) }
return JSON.parse(res.body)
end
def self.get_team_members(org, team_name)
qry = <<-'GRAPHQL'
query($org: String!, $teamName: String!) {
organization(login:$org) {
team(slug:$teamName) {
members(first:100) {
edges {
node {
id
login
name
}
}
}
}
}
}
GRAPHQL
vars = {
"org": org,
"teamName": team_name,
}
return query(qry, vars)
end
def self.get_user_by_login(login)
qry = <<-'GRAPHQL'
query($login: String!) {
user(login: $login) {
id
login
name
}
}
GRAPHQL
vars = {
"login": login
}
return query(qry, vars)
end
def self.get_my_user_login
qry = <<-'GRAPHQL'
query {
viewer {
login
}
}
GRAPHQL
return query(qry)
end
def self.get_pull_request_by_number(org, repo, pr_number)
qry = <<-'GRAPHQL'
query($repoOwner: String!, $repoName: String!, $prNumber: Int!) {
repository(owner:$repoOwner, name:$repoName) {
pullRequest(number:$prNumber) {
id
repository {
owner {
login
}
}
url
number
headRefName
baseRefName
mergeable
isDraft
commits(last:1){
nodes{
commit{
status{
state
contexts {
state
context
}
}
}
}
}
title
createdAt
author {
... on User {
id
...userFields
}
}
reviewRequests(last: 100) {
nodes {
requestedReviewer {
... on User {
...userFields
}
... on Team {
name
login: slug
}
}
}
}
reviews(last: 100) {
nodes {
author {
...userFields
...botFields
}
state
}
}
}
}
}
fragment userFields on User {
name
login
}
fragment botFields on Bot {
login
}
GRAPHQL
vars = {
repoOwner: org,
repoName: repo,
prNumber: pr_number,
}
return query(qry, vars)
end
def self.get_open_pull_requests_for_search(search)
qry = <<-'GRAPHQL'
query($queryString: String!) {
search(query:$queryString, type: ISSUE, first: 100) {
edges {
node {
... on PullRequest {
id
repository {
isArchived
owner {
login
}
}
url
number
headRefName
baseRefName
mergeable
isDraft
commits(last:1){
nodes{
commit{
status{
state
contexts {
state
context
}
}
}
}
}
title
createdAt
author {
... on User {
id
...userFields
}
}
reviewRequests(last: 100) {
nodes {
requestedReviewer {
... on User {
...userFields
}
... on Team {
name
login: slug
}
}
}
}
reviews(last: 100) {
nodes {
author {
...userFields
...botFields
}
state
}
}
}
}
}
}
}
fragment userFields on User {
name
login
}
fragment botFields on Bot {
login
}
GRAPHQL
vars = {
queryString: "is:open is:pr #{search}"
}
return query(qry, vars)
end
def self.get_any_pull_request_ids_for_repo(search)
qry = <<-'GRAPHQL'
query($queryString: String!) {
search(query:$queryString, type: ISSUE, first: 100) {
edges {
node {
... on PullRequest {
id
}
}
}
}
}
GRAPHQL
vars = {
queryString: "is:pr #{search}"
}
return query(qry, vars)
end
def self.get_open_pull_requests_for_author(login, extra_filters="")
return get_open_pull_requests_for_search("author:#{login} #{extra_filters}")
end
def self.get_open_pull_requests_for_involves(login, extra_filters="")
# https://help.github.com/en/github/searching-for-information-on-github/searching-issues-and-pull-requests#search-by-a-user-thats-involved-in-an-issue-or-pull-request
# involves = OR between the author, assignee, mentions, and commenter
# ... not sure if it includes review-requested:#{login} -- seems like maybe yes?
return get_open_pull_requests_for_search("involves:#{login} #{extra_filters}")
end
def self.get_open_pull_requests_for_team(team, extra_filters="")
# team:#{org}/#{team_name}
# not sure if it also includes team-review-requested:#{org}/#{team_name} ?
return get_open_pull_requests_for_search("team:#{team} #{extra_filters}")
end
def self.get_open_pull_requests_for_repo(repo, extra_filters="")
return get_open_pull_requests_for_search("repo:#{repo} #{extra_filters}")
end
def self.request_review_on_pull_request(pr_id, user_ids)
qry = <<-'GRAPHQL'
mutation($pullRequestId: ID!, $userIds: [ID!]) {
requestReviews(input: { pullRequestId: $pullRequestId, userIds: $userIds, union: true }) {
pullRequest {
id
},
}
}
GRAPHQL
vars = {
pullRequestId: pr_id,
userIds: user_ids
}
return query(qry, vars)
end
end
|
class AddRecommendationToMeasureSelections < ActiveRecord::Migration
def change
add_column :measure_selections, :recommendation, :string
end
end
|
class CreateHairservices < ActiveRecord::Migration[6.0]
def change
create_table :hairservices do |t|
t.string :service_name
t.integer :price
t.integer :hairstylist_id
# t.timestamps
end
end
end
|
module Chitchat
module Client
class Message
attr_accessor :from, :body
def initialize(attrs)
@from = attrs['user']
@body = attrs['body']
end
end
end
end
|
require "aruba/cucumber"
PROJECT_ROOT =
File.expand_path(File.join(File.dirname(__FILE__), "..", "..")).freeze
Aruba.configure do |config|
config.exit_timeout = Integer ENV.fetch("ARUBA_TIMEOUT", 120)
end
if RUBY_PLATFORM == "java"
Aruba.configure do |config|
config.before_cmd do
# disable JIT since these processes are so short lived
set_env("JRUBY_OPTS", "-X-C #{ENV["JRUBY_OPTS"]}")
java_options = ENV["JAVA_OPTS"]
if 1.size == 4 # 4 for 32 bit java, 8 for 64 bit java.
set_env("JAVA_OPTS", "-d32 #{java_options}")
else
set_env(
"JAVA_OPTS",
"-XX:+TieredCompilation -XX:TieredStopAtLevel=1 #{java_options}"
)
end
end
end
end
|
class Like < ApplicationRecord
belongs_to :user
belongs_to :blog
after_save :update_like_count
private
def update_like_count
blog.update_column(:likes_count, blog.likes.sum(:hits))
end
end |
class GreeterController < ApplicationController
def hello
random_names = ["John", "Lisa", "Joe", "Jenny", "Michael"]
@name = random_names.sample
@time = Time.now
end
def goodbye
end
end
|
require_relative 'menu'
class Order
attr_reader :order, :amount
def initialize
@order = []
@amount = []
end
def add_to_order menu, dish, quantity
dish_included?(menu, dish)
amount << quantity
order << dish
end
def total_price
total = 0
order.each_with_index do |item, index|
total += (item.price * amount[index])
end
total
end
def show_order
output = ''
order.each_with_index do |dish, index|
output += "\n#{dish.show_details} X#{amount[index]}"
end
output
end
def place_order(payment)
fail "Incorrect Payment" if payment != total_price
show_order
total_price
Text.new.send_text
end
private
def dish_included?(menu, dish)
fail 'Item not on menu' if menu.dishes.include?(dish) == false
end
end
|
class AuthenticationController < ApplicationController
def create
user = users_repository.find_by_email(email)
if user.authenticate(password)
token = JsonWebToken.encode(user_id: user.id)
cookies.encrypted[:jwt] = {
value: token,
httponly: true,
expires: 1.week.from_now.utc,
}
render json: {name: user.name}, status: 201
else
render json: {}, status: :unauthorized
end
end
def destroy
cookies.delete(:jwt)
head :ok
end
private
def user_params
params.require(:user).permit(:email, :password)
end
def email
user_params[:email]
end
def password
user_params[:password]
end
def users_repository
@users_repository ||= UsersRepository.new(rom)
end
end
|
# encoding: UTF-8
class SubGroup < ActiveRecord::Base
attr_accessible :description, :name, :image, :category_id
validates :name, :uniqueness => {:message => 'عنوان تکراری است'}
validates :name, :presence => {:message => 'عنوان را بنویسید'}
has_attached_file :image, :styles => { :small => "150x150#", :medium => "200X200>", :original => "350X350>" }
extend FriendlyId
friendly_id :name
has_many :products
belongs_to :category
end
|
require 'spec_integration_helper'
feature 'Common use cases > Simple action' do
let(:cat_owner) { test_app_page.cat_owner }
let(:test_app_page) { HomePage.new }
let(:applier) do
SPV::Applier.new(test_app_page) do
fixtures ['ned_stark']
waiter &:wait_for_cat_owner
end
end
let(:applier_with_event) do
applier.shift_event {
test_app_page.link_with_one_request.click
}
end
before do
test_app_page.load
end
context 'do action and handles one HTTP request' do
it 'applies a default fixture' do
applier_with_event.apply_vcr
expect(cat_owner).to have_content('Ned Stark')
end
end
end |
#copied from: http://lucatironi.net/tutorial/2015/08/23/rails_api_authentication_warden/?utm_source=rubyweekly&utm_medium=email
require 'rails_helper'
RSpec.describe AuthenticationTokenStrategy, type: :model do
let!(:user) {
User.create(email: "user@example.com", password: "password")
}
let!(:authentication_token) {
AuthenticationToken.create(user_id: user.id,
body: "token",
last_used_at: DateTime.current)
}
let(:env) {
{ "HTTP_X_USER_EMAIL" => user.email,
"HTTP_X_AUTH_TOKEN" => authentication_token.body }
}
let(:subject) { described_class.new(nil) }
describe "#valid?" do
context "with valid credentials" do
before { allow(subject).to receive(:env).and_return(env) }
it { is_expected.to be_valid }
end
context "with invalid credentials" do
before { allow(subject).to receive(:env).and_return({}) }
it { is_expected.not_to be_valid }
end
end
describe "#authenticate!" do
context "with valid credentials" do
before { allow(subject).to receive(:env).and_return(env) }
it "returns success" do
expect(User).to receive(:find_by)
.with(email: user.email)
.and_return(user)
expect(TokenIssuer).to receive_message_chain(:build, :find_token)
.with(user, authentication_token.body)
.and_return(authentication_token)
expect(subject).to receive(:success!).with(user)
subject.authenticate!
end
it "touches the token" do
expect(subject).to receive(:touch_token)
.with(authentication_token)
subject.authenticate!
end
end
context "with invalid user" do
before { allow(subject).to receive(:env)
.and_return({ "HTTP_X_USER_EMAIL" => "invalid@email",
"HTTP_X_AUTH_TOKEN" => "invalid-token" }) }
it "fails" do
expect(User).to receive(:find_by)
.with(email: "invalid@email")
.and_return(nil)
expect(TokenIssuer).not_to receive(:build)
expect(subject).not_to receive(:success!)
expect(subject).to receive(:fail!)
subject.authenticate!
end
end
context "with invalid token" do
before do
allow(subject).to receive(:env)
.and_return({ "HTTP_X_USER_EMAIL" => user.email,
"HTTP_X_AUTH_TOKEN" => "invalid-token" })
end
it "fails" do
expect(User).to receive(:find_by)
.with(email: user.email)
.and_return(user)
expect(TokenIssuer).to receive_message_chain(:build, :find_token)
.with(user, "invalid-token")
.and_return(nil)
expect(subject).not_to receive(:success!)
expect(subject).to receive(:fail!)
subject.authenticate!
end
end
end
end
|
class Event < ApplicationRecord
belongs_to :creator, class_name: 'User', foreign_key: 'user_id'
has_many :invitations, foreign_key: 'event_id'
has_many :attendess, through: :invitations, source: :user
scope :past, -> { where('date < ?', Date.today) }
scope :upcoming, -> { where('date >= ?', Date.today) }
end
|
class UsersController < ApplicationController
skip_before_action :authenticate, only: %i(new create)
before_action :set_user, only: [:edit, :update]
def new
@user = User.new
end
def create
@user = User.new(user_params)
if @user.save
redirect_to signin_url, notice: "You've Successfully Signed up."
else
render :new
end
end
def edit
end
def update
if @user.update(user_params)
redirect_to profile_url, notice: "Your profile has been successfully updated."
else
render action: 'edit'
end
end
private
def user_params
params.require(:user).permit(:screen_name, :email, :password ,:password_confirmation)
end
def set_user
@user = current_user
end
end
|
module OnetableTerminator
class Lock
attr_reader :filename, :file
def initialize(driver)
@filename = "/tmp/onevnm-#{driver}-lock"
end
def lock
@file = File.open(filename, 'w')
file.flock(File::LOCK_EX)
end
def unlock
file.close
end
end
end
|
class InhalerDeviceType < ApplicationRecord
validates :inhaler_type_name,
presence: true,
uniqueness: { case_sensitive: false }
end |
module SimpleSpark
module Endpoints
# Provides access to the /sending-domains endpoint
# @note Example sending domain
# { "domain": "example1.com", "tracking_domain": "click.example1.com",
# "status": { "ownership_verified": true, "spf_status": "valid", "abuse_at_status": "valid",
# "abuse_at_status": "valid", "dkim_status": "valid", "compliance_status": "valid", "postmaster_at_status": "valid" } }
# @note See: https://developers.sparkpost.com/api/#/reference/sending-domains
class SendingDomains
attr_accessor :client
def initialize(client)
@client = client
end
# Lists your sending domains
# @return [Array] a list of Sending Domain hash objects
# @note See: https://developers.sparkpost.com/api/#/reference/sending-domains/create-and-list/list-all-sending-domains
def list
@client.call(method: :get, path: 'sending-domains')
end
# Create a sending domain
# @param domain_name [String] the domain name to create
# @param tracking_domain [String] the domain name to track this domain against
# @note See: https://developers.sparkpost.com/api/#/reference/sending-domains/create-and-list
def create(values)
@client.call(method: :post, path: 'sending-domains', body_values: values)
end
# Retrieve a sending domain
# @param domain_name [String] the domain name to retrieve
# @return [Hash] an Sending Domain hash object
# @note See: https://developers.sparkpost.com/api/#/reference/sending-domains/retrieve-update-and-delete
def retrieve(domain_name)
domain_name = @client.url_encode(domain_name)
@client.call(method: :get, path: "sending-domains/#{domain_name}")
end
# Update a Sending Domain by its domain name
# @param domain_name [String] the domain to update
# @param values [Hash] the values to update the sending domain with
#
# @note See: https://developers.sparkpost.com/api/#/reference/sending-domains/retrieve-update-and-delete
def update(domain_name, values)
domain_name = @client.url_encode(domain_name)
@client.call(method: :put, path: "sending-domains/#{domain_name}", body_values: values)
end
# Verify a Sending Domain by its domain name
# @param domain_name [String] the domain to verify
# @param values [Hash] the values specifying how to verify the domain
# Including the fields "dkim_verify" and/or "spf_verify" in the request initiates a check against the associated DNS record
# type for the specified sending domain.Including the fields "postmaster_at_verify" and/or "abuse_at_verify" in the request
# results in an email sent to the specified sending domain's postmaster@ and/or abuse@ mailbox where a verification link can
# be clicked.Including the fields "postmaster_at_token" and/or "abuse_at_token" in the request initiates a check of the provided
# token(s) against the stored token(s) for the specified sending domain.
#
# @note See: https://developers.sparkpost.com/api/#/reference/sending-domains/verify
def verify(domain_name, values)
domain_name = @client.url_encode(domain_name)
@client.call(method: :post, path: "sending-domains/#{domain_name}/verify", body_values: values)
end
# Delete a sending domain
# @param domain_name [String] the domain name to delete
# @note See: https://developers.sparkpost.com/api/#/reference/sending-domains/retrieve-update-and-delete
def delete(domain_name)
domain_name = @client.url_encode(domain_name)
@client.call(method: :delete, path: "sending-domains/#{domain_name}")
end
end
end
end
|
require "test_helper"
describe SupergroupSections::Sections do
include RummagerHelpers
include TaxonHelpers
let(:taxon_id) { "12345" }
let(:base_path) { "/base/path" }
let(:supergroup_sections) { SupergroupSections::Sections.new(taxon_id, base_path) }
describe "#sections" do
before(:all) do
Supergroups::PolicyAndEngagement.any_instance.stubs(:tagged_content).with(taxon_id).returns(section_tagged_content_list("case_study"))
Supergroups::Services.any_instance.stubs(:tagged_content).with(taxon_id).returns(section_tagged_content_list("form"))
Supergroups::GuidanceAndRegulation.any_instance.stubs(:tagged_content).with(taxon_id).returns(section_tagged_content_list("guide"))
Supergroups::NewsAndCommunications.any_instance.stubs(:tagged_content).with(taxon_id).returns([])
Supergroups::Transparency.any_instance.stubs(:tagged_content).with(taxon_id).returns([])
Supergroups::ResearchAndStatistics.any_instance.stubs(:tagged_content).with(taxon_id).returns([])
@sections = supergroup_sections.sections
end
it "returns a list of sections with tagged content" do
assert 5, @sections.length
end
it "returns a list of supergroup details" do
section_details = %i[
id
title
promoted_content
documents
partial_template
see_more_link
show_section
]
@sections.each do |section|
assert_equal(section_details, section.keys)
end
end
it "each section has an id" do
expected_ids = %w[
services
guidance_and_regulation
news_and_communications
policy_and_engagement
transparency
research_and_statistics
]
section_ids = @sections.map { |section| section[:id] }
section_ids.map do |id|
assert_includes expected_ids, id
end
assert expected_ids, section_ids
end
it "knows if each sections should be shown or not" do
shown_sections = @sections.select { |section| section[:show_section] == true }
not_show_sections = @sections.select { |section| section[:show_section] == false }
assert 3, shown_sections.length
assert 2, not_show_sections.length
end
end
end
|
class LocationSerializer < ActiveModel::Serializer
include Pundit
attributes :id,
:company,
:address_line1,
:address_line2,
:postal_code,
:city,
:state_province,
:country,
:phone_number,
:can_update,
:can_delete
def can_update
policy(object).update?
end
def can_delete
policy(object).destroy?
end
def pundit_user
scope
end
end
|
class CreateRegistrations < ActiveRecord::Migration
def change
create_table :registrations do |t|
t.integer :waitlist_place
t.boolean :payment_received
t.timestamps
end
end
end
|
class SheltersController < ApplicationController
before_action :require_admin
def index
@shelters = Shelter.all
end
def new
@shelter = Shelter.new
end
def create
@shelter = Shelter.new(shelter_params)
if @shelter.save
redirect_to shelter_path(@shelter)
else
render :new
end
end
def show
@shelter = Shelter.find(params[:id])
render :show
end
def edit
@shelter = Shelter.find(params[:id])
if current_user.admin
render :edit
elsif current_user == @user
render :edit
else
redirect_to root_path
end
end
def update
@shelter = Shelter.find(shelter[:id])
@shelter.update(shelter_params)
if @shelter.save
redirect_to shelter_path(@shelter)
else
render :edit
end
end
private
def shelter_params
params.require(:shelter).permit(:name, :physical_address)
end
end
|
require_relative 'associatable'
module Associatable
def has_one_through(name, through_name, source_name)
define_method(name) do
through_options = self.class.assoc_options[through_name]
source_options = through_options.model_class.assoc_options[source_name]
through_table = through_options.model_class.table_name
source_table = source_options.model_class.table_name
res = DBConnection.execute2(<<-SQL)
SELECT
#{source_table}.*
FROM
#{through_table}
JOIN
#{source_table} ON #{through_table}.#{source_options.foreign_key} = #{source_table}.id
WHERE
#{through_table}.id = #{self.send(through_options.foreign_key)}
SQL
source_options.model_class.parse_all(res.drop(1)).first
end
end
end
|
module WsdlMapper
module CoreExt
# A very simple representation of time durations.
# The implementation is very naive. Each component (years, months, etc...) is stored separately
# and equality is only given, if all components are the same:
# ```ruby
# TimeDuration.new(years: 1) == TimeDuration.new(months: 12)
# #=> false
# ```
# Furthermore, comparison (`<=>`) does not work if you use unnormalized durations (e.g. 15 months instead of 1 year, 3 months):
# ```ruby
# TimeDuration.new(years: 1, months: 2) < TimeDuration.new(months: 15)
# #=> false
# ```
class TimeDuration
# @!attribute years
# @return [Fixnum] This durations years
# @!attribute months
# @return [Fixnum] This durations months
# @!attribute days
# @return [Fixnum] This durations days
# @!attribute hours
# @return [Fixnum] This durations hours
# @!attribute minutes
# @return [Fixnum] This durations minutes
# @!attribute seconds
# @return [Fixnum] This durations seconds
# @!attribute negative
# @return [true, false] Is this duration negative?
attr_accessor :years, :months, :days, :hours, :minutes, :seconds, :negative
# @param [bool] negative Set if negative or not
# @param [Fixnum] years Sets the years
# @param [Fixnum] months Sets the months
# @param [Fixnum] days Sets the days
# @param [Fixnum] hours Sets the hours
# @param [Fixnum] minutes Sets the minutes
# @param [Fixnum] seconds Sets the seconds
def initialize(negative: false, years: 0, months: 0, days: 0, hours: 0, minutes: 0, seconds: 0)
@seconds = seconds
@minutes = minutes
@hours = hours
@days = days
@months = months
@years = years
@negative = negative
end
# Check if this is a negative duration
# @return [true, false]
def negative?
!!@negative
end
# @private
def hash
[negative?, years, months, days, hours, minutes, seconds].hash
end
# @private
def eql?(other)
return false unless other.is_a?(TimeDuration)
negative? == other.negative? &&
years == other.years &&
months == other.months &&
days == other.days &&
hours == other.hours &&
minutes == other.minutes &&
seconds == other.seconds
end
# @private
def ==(other)
eql? other
end
# @private
def <=>(other)
return -1 if negative? and !other.negative?
return 1 if !negative? and other.negative?
fields = [:years, :months, :days, :hours, :minutes, :seconds]
fields.each do |field|
c = send(field) <=> other.send(field)
return c if c != 0
end
return 0
end
# @private
def >(other)
(self <=> other) > 0
end
# @private
def >=(other)
(self <=> other) >= 0
end
# @private
def <(other)
(self <=> other) < 0
end
# @private
def <=(other)
(self <=> other) <= 0
end
end
end
end
|
require 'spec_helper'
describe Renoval::Validators::Base do
describe '#validate' do
let(:content) {}
let(:type) {}
let(:klass) { double(type) }
before :each do
allow(File).to receive(:open).with(anything, 'r').and_return(content)
end
context 'bug' do
let(:type) { 'Bug' }
let(:content) { "Bugs: [AC-1111]()https://jira.sage.com/browse/AC-1111 - Test text" }
before :each do
allow(Renoval::Validators::Bug).to receive(:new).and_return(klass)
end
it 'uses the Bug class' do
expect(klass).to receive(:validate_type_line)
subject.validate('AC-1111.yml')
end
end
context 'improvement' do
let(:klass) { double('Improvement') }
let(:content) { "Improvements: [S1PRT-1111]()https://jira.sage.com/browse/S1PRT-1111 - Test text" }
before :each do
allow(Renoval::Validators::Improvement).to receive(:new).and_return(klass)
end
it 'uses the Improvement class' do
expect(klass).to receive(:validate_type_line)
subject.validate('S1PRT-1111.yml')
end
end
context 'minor improvement' do
let(:klass) { double('Minor Improvement') }
let(:content) { "Minor Improvements: [S1PRT-1111]()https://jira.sage.com/browse/S1PRT-1111 - Test text" }
before :each do
allow(Renoval::Validators::MinorImprovement).to receive(:new).and_return(klass)
end
it 'uses the MinorImprovement class' do
expect(klass).to receive(:validate_type_line)
subject.validate('S1PRT-1111.yml')
end
end
end
end
|
require 'SimpleCov'
SimpleCov.start
require 'minitest/autorun'
require 'minitest/pride'
require './lib/complete_me.rb'
class CompleteMeTest < Minitest::Test
def test_creates_head_node
complete_me = CompleteMe.new
my_head = complete_me.head
assert_equal Node, my_head.class
end
def test_creates_other_nodes
complete_me = CompleteMe.new
my_head = complete_me.head
complete_me.insert("a")
assert_equal Node, my_head.a.class
end
def test_creates_nested_nodes
complete_me = CompleteMe.new
my_head = complete_me.head
complete_me.insert("aa")
assert_equal Node, my_head.a.a.class
end
def test_can_insert_other_words
complete_me = CompleteMe.new
my_head = complete_me.head
complete_me.insert("dog")
assert_equal Node, my_head.d.o.g.class
end
def test_can_tell_whether_a_path_is_a_word
complete_me = CompleteMe.new
my_head = complete_me.head
complete_me.insert("dog")
assert my_head.d.o.g.is_word?
end
def test_can_tell_whether_a_path_is_not_a_word
complete_me = CompleteMe.new
my_head = complete_me.head
complete_me.insert("dog")
assert_equal false, my_head.d.is_word?
end
def test_can_import_newline_seperated_list_of_words
complete_me = CompleteMe.new
my_head = complete_me.head
complete_me.populate("dog\ncat\nfish")
assert_equal Node, my_head.d.o.g.class
assert_equal Node, my_head.c.a.t.class
assert_equal Node, my_head.f.i.s.h.class
end
def test_can_find_words_in_dictionary
complete_me = CompleteMe.new
complete_me.insert("dog")
assert_equal ["dog"], complete_me.suggest("dog")
end
def test_can_suggest_completions
complete_me = CompleteMe.new
complete_me.insert("dog")
assert_equal ["dog"], complete_me.suggest("d")
end
def test_can_suggest_multiple_completions
complete_me = CompleteMe.new
complete_me.insert("dog")
complete_me.insert("do")
assert_equal ["do", "dog"], complete_me.suggest("d")
end
def test_can_count_words_in_dictionary
complete_me = CompleteMe.new
complete_me.insert("dog")
complete_me.insert("cat")
complete_me.insert("do")
assert_equal 3, complete_me.count
end
def test_can_select_words
complete_me = CompleteMe.new
my_head = complete_me.head
complete_me.insert("dog")
complete_me.suggest("do")
complete_me.select("do", "dog")
assert_equal 1, my_head.d.o.g.weight
end
def test_selected_words_are_returned_first
complete_me = CompleteMe.new
complete_me.insert("dog")
complete_me.insert("do")
complete_me.insert("doggoneit")
complete_me.suggest("do")
complete_me.select("do", "doggoneit")
assert_equal "doggoneit", complete_me.suggest("do")[0]
end
def test_can_remove_words
complete_me = CompleteMe.new
complete_me.insert("dog")
complete_me.remove("dog")
assert_equal "This doesn't match any words.", complete_me.suggest("do")
end
def test_can_prune_tree
complete_me = CompleteMe.new
my_head = complete_me.head
complete_me.insert("dog")
complete_me.insert("doggoneit")
complete_me.remove("doggoneit")
assert_equal nil, my_head.d.o.g.g
assert_equal Node, my_head.d.o.g.class
end
def test_can_note_capitalized_words
complete_me = CompleteMe.new
my_head = complete_me.head
complete_me.insert("Brendan")
assert my_head.b.r.e.n.d.a.n.is_capitalized?
end
def test_can_suggest_capitalized_words
complete_me = CompleteMe.new
my_head = complete_me.head
complete_me.insert("Brendan")
assert_equal ["Brendan"], complete_me.suggest("B")
end
end
|
require 'minitest_helper'
class TestFileProfile < MiniTest::Unit::TestCase
def setup
@sample_filename = 'duplicate_filename_1.sample'
@sample_relative_path = File.join('./test/sample_for_test/dir_a1/', @sample_filename)
@sample_fullpath = File.join(test_fullpath, 'sample_for_test/dir_a1/', @sample_filename)
@sample_md5_digest = '5258bf47639b8f906c1a17aee86c54dd'
@file_profile = DuplicatedFilenameChecker::FileProfile.new(@sample_relative_path)
end
def test_basename
assert @file_profile.basename == @sample_filename
end
def test_path
assert @file_profile.path == @sample_fullpath
end
def test_md5_digest
assert @file_profile.md5_digest == @sample_md5_digest
end
def test_stat
assert @file_profile.stat.class == File::Stat
end
end
|
# == Schema Information
#
# Table name: questions
#
# id :integer not null, primary key
# quiz_id :integer
# type :string
# data :json
# created_at :datetime not null
# updated_at :datetime not null
# published :boolean
# explanation :text
#
# Indexes
#
# index_questions_on_quiz_id (quiz_id)
#
require 'rails_helper'
RSpec.describe Quizer::MultiAnswerQuestion, type: :model do
context 'associations' do
it { should belong_to(:quiz) }
end
it "has a valid factory" do
question = build(:multi_answer_question)
expect(question).to be_valid
end
describe "validations" do
it "validates data schema" do
question = Quizer::MultiAnswerQuestion.create(data:{})
expect(question.errors).to have_key(:data)
end
end
describe ".mixed_answers" do
it "returns correct and wrong answers" do
question = build(:multi_answer_question)
mixed_answers = question.mixed_answers
expect(mixed_answers.length).to eq(5)
expect(mixed_answers).to include("wrong answer a")
expect(mixed_answers).to include("wrong answer b")
expect(mixed_answers).to include("wrong answer c")
expect(mixed_answers).to include("correct answer d")
expect(mixed_answers).to include("correct answer e")
end
end
describe ".correct_answers" do
it "returns the correct answers" do
question = build(:multi_answer_question)
correct_answers = question.correct_answers
expect(correct_answers.length).to eq(2)
expect(correct_answers).to include("correct answer d")
expect(correct_answers).to include("correct answer e")
end
end
describe ".wrong_answers" do
it "returns the wrong answers" do
question = build(:multi_answer_question)
wrong_answers = question.wrong_answers
expect(wrong_answers.length).to eq(3)
expect(wrong_answers).to include("wrong answer a")
expect(wrong_answers).to include("wrong answer b")
expect(wrong_answers).to include("wrong answer c")
end
end
end
|
class AddVisitIdToContacts < ActiveRecord::Migration[6.0]
def change
add_column :contacts, :visit_id, :bigint
end
end
|
class DataSource < ActiveRecord::Base
has_many :data_providers
has_many :access_rules
has_many :data_source_imports
has_many :name_indices, :dependent => :destroy
has_many :import_schedulers
has_many :data_source_contributors, :dependent => :destroy
has_many :users, :through => :data_source_contributors
has_many :name_strings, :through => :name_indices
belongs_to :uri_type
belongs_to :response_format
URL_RE = /^https?:\/\/|^\s*$/
validates_presence_of :title, :message => "is required"
validates_presence_of :data_url, :message => "^Names Data URL is required"
validates_format_of :data_url, :with => URL_RE, :message => "^Names Data URL should be a URL"
validates_format_of :logo_url, :with => URL_RE, :message => "^Logo URL should be a URL"
validates_format_of :web_site_url, :with => URL_RE, :message => "^Website URL should be a URL"
def contributor?(a_user)
!!self.users.include?(a_user)
end
end
|
class WorkerTask < ActiveRecord::Base
belongs_to :worker
belongs_to :task
#before_create :must_be_done
def finish
self.update(done: true)
end
def must_be_done
self.done = false
end
end
|
# -*- mode: ruby -*-
# vi: set ft=ruby :
Vagrant.configure(2) do |config|
# For a complete reference, please see the online documentation at
# https://docs.vagrantup.com.
config.vm.box = "ubuntu/trusty64"
config.vm.network "forwarded_port", guest: 3000, host: 3000
config.vm.network "forwarded_port", guest: 4000, host: 4000
config.vm.provider "virtualbox" do |vb|
vb.memory = 2048
vb.name = "Pancake_Project"
vb.cpus = 2
end
config.vm.provision "shell", path: "prereqs.sh", privileged: false
config.vm.provision "shell", path: "autoDev.sh", privileged: false
end
|
require 'fileutils'
require 'logger'
require 'mini_magick'
module Rails
module WebP
class Converter
class << self
attr_reader :context
def convert_to_webp(input_path, output_path)
# Ex: convert wizard.png -quality 50 -define webp:lossless=true wizard.webp
MiniMagick::Tool::Convert.new do |convert|
convert << input_path
options = WebP.encode_options
convert << '-quality' << options[:quality]
options.except(:quality).each do |name, value|
convert << "-define" << "webp:#{name.to_s.dasherize}=#{value}"
end
convert << output_path
end
end
def process(input_path, data, context, app = Rails.application)
return data if excluded_dir?(input_path)
@context = context
prefix = app.config.assets.prefix
digest = data_digest(data)
webp_file = webp_file_name(data, digest)
output_path = Pathname.new(File.join(app.root, 'public', prefix, webp_file))
if WebP.force || !webp_file_exists?(digest, output_path)
FileUtils.mkdir_p(output_path.dirname) unless Dir.exists?(output_path.dirname)
# TODO: check app.assets.gzip and act accordingly
convert_to_webp(input_path, output_path)
logger&.info "Writing #{output_path}"
end
data
end
private
def data_digest(data)
"-#{context.environment.digest_class.new.update(data).to_s}"
end
def excluded_dir?(path)
regex = WebP.exclude_dir_regex
return false unless regex
!!path.match(regex)
end
def webp_file_name(data, digest)
file_name = context.logical_path # Original File name w/o extension
file_ext = File.extname(context.filename) # Original File extension
"#{file_name}#{digest}.webp" # WebP File fullname
end
def webp_file_exists?(digest, output_path)
File.exists?(output_path) && digest == output_path.to_s.split('-').last.split('.').first
end
def logger
if context && context.environment
context.environment.logger
else
logger = Logger.new($stderr)
logger.level = Logger::FATAL
logger
end
end
end
end
end
end
|
module BuildLights
class Lights
RED = 1
GREEN = 2
def initialize(implementation = BottleRocket)
@implementation = implementation
end
def success
@implementation.turn_on GREEN
@implementation.turn_off RED
end
def failed
@implementation.turn_on RED
@implementation.turn_off GREEN
end
end
class BottleRocket
def self.turn_on(unit, house='A')
send('on', unit, house)
end
def self.turn_off(unit, house='A')
send('off', unit, house)
end
private
def self.send(command, unit, house)
cmd = "br -v --house=#{house} --#{command}=#{unit}"
puts "sending X10 command -> #{cmd}" if $verbose
system cmd
raise "bottlerocket command failed with status code #{$?.exitstatus}" if $?.exitstatus > 0
end
end
end
|
describe "Upload", :Upload, :smoke do
before(:each) do
visit "/upload"
#Criando arquivos
@arquivo = Dir.pwd + "/spec/fixtures/arquivo.txt"
@imagem = Dir.pwd + "/spec/fixtures/imagem.png"
end
it "upload com arquivo texto" do
attach_file("file-upload", @arquivo) #Anexe o arquivo no "file-upload", sendo o arquivo "@arquivo"
click_button "Upload"
div_arquivo = find("#uploaded-file") #Descubra a div_arquivo no "#uploaded-file"
expect(div_arquivo.text).to eql "arquivo.txt" #Esperado que o texto da div_arquivo seja igual "arquivo.txt"(nome do arquivo)
end
it "upload de imagem" do
attach_file("file-upload", @imagem) #Anexe a imagem no "file-upload", sendo a imagem "@imagem"
click_button "Upload"
img = find("#new-image") #Descubra a img no "#new-image"
expect(img[:src]).to include "imagem.png" #Esperado que o src da imagem inclua o "imagem.png"(Título da imagem)
end
end
|
require "money"
module Menthol
class Account
def initialize(provider, name, amount, type, currency)
@provider = provider
@name = name
@type = type.to_sym
@currency = Money::Currency.find(currency)
@amount = Money.new(amount || 0, @currency.iso_code)
end
def self.open(provider, configuration)
new(
provider,
configuration["name"],
configuration["amount"],
configuration["type"],
configuration["currency"]
)
end
attr_reader :provider
attr_reader :name
attr_reader :type
attr_reader :amount
attr_reader :currency
def parse_amount(raw_amount)
amount = raw_amount.gsub(/[^\d\.]/, "").to_f
amount_subunit = amount * @currency.subunit_to_unit
@amount = Money.new(amount_subunit, @currency.iso_code)
end
end
end
|
class RolesController < ApplicationController
before_action :load_company
before_action :load_role, only: [:show, :edit, :update, :destroy]
# GET /roles
def index
@roles = @company.roles.ordered
end
# GET /roles/1
def show
end
# GET /roles/new
def new
@role = @company.roles.new
end
# GET /roles/1/edit
def edit
end
# POST /roles
def create
@role = @company.roles.new(safe_params)
if @role.save
redirect_to [@company, @role], notice: "#{Role.model_name.human} was successfully created."
else
render :new
end
end
# PATCH/PUT /roles/1
def update
if @role.update(safe_params)
redirect_to [@company, @role], notice: "#{Role.model_name.human} was successfully updated."
else
render :edit
end
end
# DELETE /roles/1
def destroy
@role.destroy
redirect_to company_roles_url(@company), notice: "#{Role.model_name.human} was successfully removed."
end
private
def load_company
@company = Company.find(params[:company_id])
end
# Use callbacks to share common setup or constraints between actions.
def load_role
@role = @company.roles.find(params[:id])
end
# Only allow a trusted parameter "white list" through.
def safe_params
params.require(:role).permit(:name)
end
end
|
class CreateContactUs < ActiveRecord::Migration[5.0]
def change
create_table :contact_us do |t|
t.string :name
t.string :contact_number
t.string :contact_email_id
t.string :Tell_us_more_about_you
t.timestamps
end
end
end
|
class ApplicationController < ActionController::Base
helper_method :xeditable?
protect_from_forgery with: :exception
def xeditable? object = nil
true # Or something like current_user.xeditable?
end
end
|
class ArmGroupRatingIntro < PdfReport
def initialize(quote=[],account=[],policy_calculation=[],view)
super()
@quote = quote
@account = account
@policy_calculation = policy_calculation
@view = view
@group_fees =
if @quote.fees.nil?
0
else
@quote.fees
end
@current_date = DateTime.now.to_date
intro_page
end
private
def intro_page
header
move_down 20
current_cursor = cursor
bounding_box([50, (current_cursor - 10) ], :width => 100, :height => 65) do
text "#{@current_date.strftime("%B %e, %Y")}", style: :bold
transparent(0) { stroke_bounds }
end
bounding_box([250, current_cursor], :width => 170, :height => 75) do
text "#{@account.representative.quote_year} Projected Discount:", style: :bold
move_down 5
text "Total Premium Savings Estimate: ", style: :bold
transparent(0) { stroke_bounds }
end
bounding_box([425, current_cursor], :width => 75, :height => 75) do
text "#{percent(@account.group_rating_tier)}", style: :bold
move_down 5
text "#{price(@account.group_savings - @group_fees)}", style: :bold
transparent(0) { stroke_bounds }
end
text "#{@account.name.titleize}"
text "#{@account.street_address.titleize} #{@account.street_address_2}"
text "#{@account.city.titleize}, #{@account.state.upcase} #{@account.zip_code}"
move_down 25
current_cursor = cursor
bounding_box([0, current_cursor], :width => 25, :height => 25) do
text "RE:", style: :bold, size: 10
transparent(0) { stroke_bounds }
end
bounding_box([25, current_cursor], :width => 250, :height => 25) do
text "OHIO WORKERS’ COMPENSATION GROUP RATING", size: 10
text "IMMEDIATE RESPONSE REQUIRED", style: :bold, size: 10
transparent(0) { stroke_bounds }
end
move_down 15
text "Congratulations! <b>#{@account.name}</b> is invited to participate in #{ @account.representative.abbreviated_name }’s #{@account.representative.quote_year} <b><u>Group Rating Program</u></b>. We have designed a program that includes the best representation, claims administration, and group premium discounts for Ohio employers through the Northeast Ohio Safety Council.", size: 11, inline_format: true
move_down 15
text "Please find the enclosed #{@account.representative.quote_year} group quote and premium projection. We stand behind our estimations for their accuracy.", size: 11
move_down 15
text "Enrollment is simple - please complete and return the enclosed forms (listed below) with a copy of the invoice and your check for the management fee by November 1, #{@account.representative.program_year}:", size: 11
move_down 15
text "1. FORM AC-26, EMPLOYER STATEMENT FOR GROUP RATING", size: 9
text "2. FORM AC-2, PERMANENT AUTHORIZATION (please include your email to receive important reminders and updates)", size: 9
text "3. GROUP RATING QUESTIONAIRE", size: 9
text "4. Fees* of #{ price(@quote.fees) } –payable to #{@account.representative.abbreviated_name} *fees are all- inclusive ", size: 9
move_down 15
text "Our goal is to provide you with the best service at the most cost effective rates possible. If you receive a better offer, we will <b>match your best verifiable Group Rating Proposal.</b>", inline_format: true
move_down 15
if [2, 9,10,16].include? @account.representative.id
text "Thank you for allowing us to prepare the following quote. If you have any questions, please contact us at (MMHR PHONE NUMBER)."
else
text "Thank you for allowing us to prepare the following quote. If you have any questions, please contact us at (614) 219-1290."
end
move_down 15
text "Sincerely,"
move_down 15
if [2,9,10,16].include? @account.representative.id
text "Signature"
text "MMHR President"
text "President"
else
image "#{Rails.root}/app/assets/images/Doug's signature.jpg", height: 50
text "Doug Maag"
text "President"
end
bounding_box([0, 50], :width => 550, :height => 50) do
if [2].include? @account.representative.id
text "COSE FOOTER", align: :center, color: "333333"
text "COSE FOOTER", align: :center, color: "333333"
text "COSE FOOTER", align: :center, color: "333333"
text "COSE FOOTER", align: :center, color: "333333"
elsif [9,10,16].include? @account.representative.id
text "MMHR FOOTER", align: :center, color: "333333"
text "MMHR FOOTER", align: :center, color: "333333"
text "MMHR FOOTER", align: :center, color: "333333"
text "MMHR FOOTER", align: :center, color: "333333"
elsif [17].include? @account.representative.id
text "TARTAN FOOTER", align: :center, color: "333333"
text "TARTAN FOOTER", align: :center, color: "333333"
text "TARTAN FOOTER", align: :center, color: "333333"
text "TARTAN FOOTER", align: :center, color: "333333"
else
text "Cleveland/Columbus Offices", align: :center, color: "333333"
text "Telephone (888) 235-8051 | Fax (614) 219-1292", align: :center, color: "333333"
text "Workers' Compensation & Unemployment Compensation Specialists", align: :center, color: "333333"
text "<u>www.alternativeriskmgmt.com</u>", align: :center, color: "333333", inline_format: true
end
transparent(0) { stroke_bounds }
end
end
end
|
# -*- coding: utf-8 -*-
# frozen_string_literal: true
require "helper"
require "fluent/plugin/parser_regexp_multi.rb"
class ParserRegexpMultiTest < Test::Unit::TestCase
setup do
Fluent::Test.setup
end
conf = %(
regexp_multi [
["(?<first>a)", "(?<second>b)", "(?<third>c)"],
["(?<forth>d)"]
]
)
sub_test_case "#parse" do
setup do
@parser = create_parser(conf)
end
test "regexp1 matched" do
text = "abc"
expected_result = {"first" => "a", "second" => "b", "third" => "c"}
@parser.parse(text) do |_time, record|
assert_equal(expected_result, record)
end
end
test "regexp2 matched" do
text = "d"
expected_result = {"forth" => "d"}
@parser.parse(text) do |_time, record|
assert_equal(expected_result, record)
end
end
test "no regexp matched" do
text = "1234"
@parser.parse(text) do |_time, record|
assert_nil(record)
end
end
end
private
def create_driver(conf)
Fluent::Test::Driver::Parser.new(Fluent::Plugin::ParserRegexpMulti).configure(conf)
end
def create_parser(conf)
create_driver(conf).instance
end
end
|
class Game
attr_accessor :letter, :guesses, :guess_count, :is_over
attr_reader :word
def initialize
@word = 'bananas'
@letter = letter
@is_over = false
@guesses = []
@guess_count = 0
end
def get_word (letter)
@word.split('').each do |x|
if x == letter
print x
else
print '-'
end
end
p @guesses << letter
end
def current_guess(letter)
if @guesses.include?(letter)
puts 'you already guessed this!'
else
@guesses << letter
p @guess_count += 1
end
end
def guessing
guess = @word.length
until guess == 0
puts 'Please guess a letter'
letter = gets.chomp
if guesses == 2
puts 'This is your last guess make it count'
end
guess -= 1
p @guesses << letter
end
p "You had #{@guesses.length} guesses!"
end
end
game = Game.new
game.get_word('a')
# I couldnt figoure out how to implement a method to keep updating the guessed letters against the word.
# For instance, the word was 'bananas' and I want bananas to register that i guessed 'a' AND 'n'
# I tried to attend office hours to help with this question on saturday and sunday but they were both cancelled |
class RenameTimeToTimestampInClazzs < ActiveRecord::Migration
def change
rename_column :clazzs, :time, :timestamp
end
end
|
require File.expand_path(File.dirname(__FILE__) + '/spec_helper')
describe MapQuest::Services::Directions do
let(:mapquest) { MapQuest.new 'xxx' }
describe '#route' do
it 'should be an instance of Directions' do
mapquest.directions.should be_an_instance_of MapQuest::Services::Directions
end
end
describe '#route' do
context 'to or from are not provided' do
it 'should raise an error if location is not provided' do
expect { mapquest.directions.route 'xxx' }.to raise_error ArgumentError
end
end
context 'to and from are provided' do
subject(:directions) { mapquest.directions.route 'Lancaster,PA', 'York,PA' }
it 'should receive to and from' do
fixture = fixture 'directions/route_only'
query = {
:key => 'xxx',
:from => 'Lancaster,PA',
:to => 'York,PA'
}
stub_request(:get, 'www.mapquestapi.com/directions/v1/route').with(:query => query).to_return(:body => fixture)
end
end
context 'when request is valid' do
describe MapQuest::Services::Directions::Response do
let(:max_results) { -1 }
let(:fixt) { 'directions/route_only' }
let(:thumb_maps) { true }
let(:valid_response) do
query = {
:key => 'xxx',
:from => 'Lancaster,PA',
:to => 'York,PA'
}
MapQuest::Services::Directions::Response.new fixture(fixt), query
end
it { valid_response.status[:code].should == 0 }
it { valid_response.status[:messages].should == [] }
it { valid_response.valid.should == true }
it { valid_response.locations.should be_kind_of(Array) }
it { valid_response.maneuvers.should be_kind_of(Array) }
it { valid_response.distance.should be_kind_of(Integer) }
it { valid_response.time.should be_kind_of(Integer) }
it { valid_response.route.should be_kind_of(Hash) }
end
end
context 'when invalid request' do
context 'when api key is invalid' do
let(:wrong_api_key_response) do
MapQuest::Services::Directions::Response.new fixture 'directions/invalid_key'
end
describe MapQuest::Services::Geocoding::Response do
it { wrong_api_key_response.status[:code].should == 403 }
it { wrong_api_key_response.status[:messages].first.should match /^This is not a valid key/ }
end
end
context 'when argument is invalid' do
let(:invalid_argument) do
MapQuest::Services::Geocoding::Response.new fixture 'directions/invalid_value'
end
describe MapQuest::Services::Geocoding::Response do
it { invalid_argument.status[:code].should == 400 }
it { invalid_argument.status[:messages].first.should match /^Error processing route/ }
end
end
end
end
end |
class StaticPagesController < ApplicationController
# TOC and Privacy policy generated at
# http://www.bennadel.com/coldfusion/privacy-policy-generator.htm#primary-navigation
#
# We should get a pair of legal eyes on them at some point, just in case.
def contact_us
render cell(StaticPages::Cell::ContactUs, current_account)
end
end
|
class UsersGroup < ApplicationRecord
enum role: { member: 0, moderator: 1, owner: 2, editor: 3 }
belongs_to :user
belongs_to :group
def confirm
update(accepted: true)
end
def owner?
user == group.owner
end
def self.role_priority(role)
case role.to_sym
when :owner then 4
when :moderator then 3
when :editor then 2
when :member then 1
end
end
end
|
require 'pry'
class Song
attr_accessor :name, :artist_name
@@all = []
def self.all
@@all
end
def save
self.class.all << self
end
def self.create
song = Song.new
song.save
song
end
def self.new_by_name(song_name)
song = Song.new
song.name = song_name
song
end
def self.create_by_name(song_name)
song = Song.new
song.name = song_name
song.save
song
end
def self.find_by_name(name)
@@all.find do |song|
song.name == name
end
end
def self.find_or_create_by_name(name)
if Song.find_by_name(name)
return Song.find_by_name(name)
else
Song.create_by_name(name)
end
end
def self.alphabetical
@@all.sort_by(&:name)
end
def self.new_from_filename(song_format)
song_array = song_format[0..-5].split("-")
new_song = Song.new
new_song.name = song_array[1].strip
new_song.artist_name = song_array[0].strip
new_song
end
def self.create_from_filename(song_format)
song_array = song_format[0..-5].split("-")
new_song = Song.new
new_song.name = song_array[1].strip
new_song.artist_name = song_array[0].strip
new_song.save
new_song
end
def self.destroy_all
self.all.clear
end
end
|
class User < ApplicationRecord
has_many :fav_gyms, :foreign_key => "user_id" :through => :users_gymns
has_many :gyms, :through => :climb_sessions
# host methods
has_many :hosted_climb_sessions, :foreign_key => 'host_id' :through => :climb_sessions
has_many :guests, through: :climb_sessions, :foreign_key => "guest_id"
# guest methods
has_many :climb_sessions, :foreign_key => 'guest_id'
has_many :hosts, through: :climb_sessions, :foreign_key => "host_id"
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
end
|
module CSS
class BorderUnitProperty < MarginProperty
def init(parent, name, value)
@name = name
super
end
def name
@name
end
def to_style
[@parent.try(:name), super].compact.join('-')
end
end
end
|
class VenuesController < ApplicationController
before_action :set_venue, only: [:show, :edit, :update, :destroy]
after_action :venue_authorization, only: [:new, :edit, :create, :update, :destroy]
skip_before_action :user_authorized?, only: [:index, :show]
def index
@venues = Venue.all
end
def show
@events = @venue.events.last(3)
end
def new
@venue = Venue.new
end
def edit
end
def create
@venue = Venue.new(venue_params)
if @venue.save
redirect_to @venue, notice: 'Venue was successfully created.'
else
render :new
end
end
def update
if @venue.update(venue_params)
redirect_to @venue, notice: 'Venue was successfully updated.'
else
render :edit
end
end
def destroy
@venue.destroy
redirect_to venues_url, notice: 'Venue was successfully destroyed.'
end
private
def set_venue
@venue = Venue.find(params[:id])
end
def venue_params
params.require(:venue).permit(:name, :location, :age, :email, :phone, :capacity,
:music, :dress_code, :website, :category)
end
end
|
# Generated by jeweler
# DO NOT EDIT THIS FILE DIRECTLY
# Instead, edit Jeweler::Tasks in Rakefile, and run 'rake gemspec'
# -*- encoding: utf-8 -*-
Gem::Specification.new do |s|
s.name = %q{gitgolem}
s.version = "0.1.2"
s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version=
s.authors = ["PoTa"]
s.date = %q{2011-05-10}
s.description = %q{Golem provides an easy way to host and manage access to git repositories on a server under a single user.}
s.email = %q{pota@mosfet.hu}
s.executables = ["golem", "golem-shell"]
s.extra_rdoc_files = [
"LICENSE.txt",
"README.md",
"TODO"
]
s.files = [
".document",
".yardopts",
"Gemfile",
"LICENSE.txt",
"README.md",
"Rakefile",
"bin/golem",
"bin/golem-shell",
"gitgolem.gemspec",
"lib/gitgolem.rb",
"lib/golem.rb",
"lib/golem/access.rb",
"lib/golem/command.rb",
"lib/golem/command/auth.rb",
"lib/golem/command/clear_repositories.rb",
"lib/golem/command/create_repository.rb",
"lib/golem/command/delete_repository.rb",
"lib/golem/command/environment.rb",
"lib/golem/command/save_config.rb",
"lib/golem/command/setup_db.rb",
"lib/golem/command/update_hooks.rb",
"lib/golem/command/update_keys_file.rb",
"lib/golem/config.rb",
"lib/golem/db.rb",
"lib/golem/db/pg.rb",
"lib/golem/db/postgres.sql",
"lib/golem/db/static.rb",
"lib/golem/parser.rb",
"lib/golem/version.rb",
"test/helper.rb",
"test/test_access.rb",
"test/test_config.rb",
"test/test_db.rb"
]
s.homepage = %q{http://github.com/eLod/gitgolem}
s.licenses = ["MIT"]
s.require_paths = ["lib"]
s.rubygems_version = %q{1.7.2}
s.summary = %q{Gem to host git repositories.}
s.test_files = [
"test/helper.rb",
"test/test_access.rb",
"test/test_config.rb",
"test/test_db.rb"
]
if s.respond_to? :specification_version then
s.specification_version = 3
if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then
s.add_development_dependency(%q<yard>, ["~> 0.6.0"])
s.add_development_dependency(%q<bundler>, ["~> 1.0.0"])
s.add_development_dependency(%q<jeweler>, ["~> 1.5.2"])
s.add_development_dependency(%q<rcov>, [">= 0"])
s.add_development_dependency(%q<bluecloth>, [">= 0"])
s.add_development_dependency(%q<test-unit>, ["~> 1"])
else
s.add_dependency(%q<yard>, ["~> 0.6.0"])
s.add_dependency(%q<bundler>, ["~> 1.0.0"])
s.add_dependency(%q<jeweler>, ["~> 1.5.2"])
s.add_dependency(%q<rcov>, [">= 0"])
s.add_dependency(%q<bluecloth>, [">= 0"])
s.add_dependency(%q<test-unit>, ["~> 1"])
end
else
s.add_dependency(%q<yard>, ["~> 0.6.0"])
s.add_dependency(%q<bundler>, ["~> 1.0.0"])
s.add_dependency(%q<jeweler>, ["~> 1.5.2"])
s.add_dependency(%q<rcov>, [">= 0"])
s.add_dependency(%q<bluecloth>, [">= 0"])
s.add_dependency(%q<test-unit>, ["~> 1"])
end
end
|
require_relative '../project_reimbursement_calculator'
require 'date'
# rubocop:disable Metrics/BlockLength
RSpec.describe ProjectReimbursementCalculator do
it 'runs set #1 as expected' do
calc = ProjectReimbursementCalculator.new(build(:set, :set1))
expect(calc.run).to eq(165)
end
it 'runs set #2 as expected' do
calc = ProjectReimbursementCalculator.new(build(:set, :set2))
expect(calc.run).to eq(590)
end
it 'runs set #3 as expected' do
calc = ProjectReimbursementCalculator.new(build(:set, :set3))
expect(calc.run).to eq(445)
end
it 'runs set #4 as expected' do
calc = ProjectReimbursementCalculator.new(build(:set, :set4))
expect(calc.run).to eq(185)
end
describe('#total_range') do
it('returns range for all projects') do
project1 = build(:project, :low_cost, start_date: Date.new(2015, 9, 1), end_date: Date.new(2015, 9, 1))
project2 = build(:project, :low_cost, start_date: Date.new(2015, 9, 5), end_date: Date.new(2015, 9, 6))
calc = ProjectReimbursementCalculator.new([project1])
expect(calc.send(:total_range)).to eq(project1.start_date..project1.end_date)
calc = ProjectReimbursementCalculator.new([project1, project2])
expect(calc.send(:total_range)).to eq(project1.start_date..project2.end_date)
end
end
describe('#project_for') do
it('returns project for the day when only one project matches') do
project1 = build(:project, :low_cost, start_date: Date.new(2015, 9, 1), end_date: Date.new(2015, 9, 3))
calc = ProjectReimbursementCalculator.new([project1])
expect(calc.send(:project_for, Date.new(2015, 9, 2))).to eq(project1)
end
it('returns first project for the day when more than one project matches') do
project1 = build(:project, :low_cost, start_date: Date.new(2015, 9, 1), end_date: Date.new(2015, 9, 3))
project2 = build(:project, :low_cost, start_date: Date.new(2015, 9, 3), end_date: Date.new(2015, 9, 6))
calc = ProjectReimbursementCalculator.new([project1, project2])
expect(calc.send(:project_for, Date.new(2015, 9, 3))).to eq(project1)
end
it('returns prev, current, and next project for given day') do
project1 = build(:project, :low_cost, start_date: Date.new(2015, 9, 1), end_date: Date.new(2015, 9, 1))
project2 = build(:project, :low_cost, start_date: Date.new(2015, 9, 2), end_date: Date.new(2015, 9, 2))
project3 = build(:project, :low_cost, start_date: Date.new(2015, 9, 3), end_date: Date.new(2015, 9, 3))
calc = ProjectReimbursementCalculator.new([project1, project2, project3])
calc.instance_variable_set(:@current_day, Date.new(2015, 9, 2))
expect(calc.send(:prev_project)).to eq(project1)
expect(calc.send(:current_project)).to eq(project2)
expect(calc.send(:next_project)).to eq(project3)
end
end
describe('#no_work_yesterday_or_tomorrow?') do
it('returns true if no projects for yesterday and tomorrow') do
calc = ProjectReimbursementCalculator.new([])
calc.instance_variable_set(:@current_day, Date.new(2015, 9, 2))
expect(calc.send(:no_work_yesterday_or_tomorrow?)).to be_truthy
end
it('returns true if project defined for yesterday') do
project1 = build(:project, :low_cost, start_date: Date.new(2015, 9, 1), end_date: Date.new(2015, 9, 1))
calc = ProjectReimbursementCalculator.new([project1])
calc.instance_variable_set(:@current_day, Date.new(2015, 9, 2))
expect(calc.send(:no_work_yesterday_or_tomorrow?)).to be_truthy
end
it('returns true if project defined for tomorrow') do
project1 = build(:project, :low_cost, start_date: Date.new(2015, 9, 3), end_date: Date.new(2015, 9, 3))
calc = ProjectReimbursementCalculator.new([project1])
calc.instance_variable_set(:@current_day, Date.new(2015, 9, 2))
expect(calc.send(:no_work_yesterday_or_tomorrow?)).to be_truthy
end
it('returns false if project defined for yesterday and tomorrow') do
project1 = build(:project, :low_cost, start_date: Date.new(2015, 9, 1), end_date: Date.new(2015, 9, 1))
project2 = build(:project, :low_cost, start_date: Date.new(2015, 9, 3), end_date: Date.new(2015, 9, 3))
calc = ProjectReimbursementCalculator.new([project1, project2])
calc.instance_variable_set(:@current_day, Date.new(2015, 9, 2))
expect(calc.send(:no_work_yesterday_or_tomorrow?)).to be_falsey
end
end
end
# rubocop:enable Metrics/BlockLength
|
class LocationPrototype < ActiveRecord::Base
self.primary_key = :code
attr_accessible :code, :location_type, :area_code, :name, :description,
:template, :layout, :options
serialize :options
belongs_to :area, :foreign_key => :area_code
has_many :actions, :as => :parent
end
|
# frozen_string_literal: true
begin
require "rspec/core/rake_task"
RSpec::Core::RakeTask.new(:spec) do |spec|
spec.pattern = "spec/**{,/*/**}/*_spec.rb"
end
rescue LoadError
warn("Cannot load rspec task.")
end
|
#!/usr/bin/env ruby
require 'pry'
require 'time'
# https://adventofcode.com/2018/day/4
# You've sneaked into another supply closet - this time, it's across from the prototype suit manufacturing lab. You need to sneak inside and fix the issues with the suit, but there's a guard stationed outside the lab, so this is as close as you can safely get.
# As you search the closet for anything that might help, you discover that you're not the first person to want to sneak in. Covering the walls, someone has spent an hour starting every midnight for the past few months secretly observing this guard post! They've been writing down the ID of the one guard on duty that night - the Elves seem to have decided that one guard was enough for the overnight shift - as well as when they fall asleep or wake up while at their post (your puzzle input).
# For example, consider the following records, which have already been organized into chronological order:
# [1518-11-01 00:00] Guard #10 begins shift
# [1518-11-01 00:05] falls asleep
# [1518-11-01 00:25] wakes up
# [1518-11-01 00:30] falls asleep
# [1518-11-01 00:55] wakes up
# [1518-11-01 23:58] Guard #99 begins shift
# [1518-11-02 00:40] falls asleep
# [1518-11-02 00:50] wakes up
# [1518-11-03 00:05] Guard #10 begins shift
# [1518-11-03 00:24] falls asleep
# [1518-11-03 00:29] wakes up
# [1518-11-04 00:02] Guard #99 begins shift
# [1518-11-04 00:36] falls asleep
# [1518-11-04 00:46] wakes up
# [1518-11-05 00:03] Guard #99 begins shift
# [1518-11-05 00:45] falls asleep
# [1518-11-05 00:55] wakes up
# Timestamps are written using year-month-day hour:minute format. The guard falling asleep or waking up is always the one whose shift most recently started. Because all asleep/awake times are during the midnight hour (00:00 - 00:59), only the minute portion (00 - 59) is relevant for those events.
# Visually, these records show that the guards are asleep at these times:
# Date ID Minute
# 000000000011111111112222222222333333333344444444445555555555
# 012345678901234567890123456789012345678901234567890123456789
# 11-01 #10 .....####################.....#########################.....
# 11-02 #99 ........................................##########..........
# 11-03 #10 ........................#####...............................
# 11-04 #99 ....................................##########..............
# 11-05 #99 .............................................##########.....
# The columns are Date, which shows the month-day portion of the relevant day; ID, which shows the guard on duty that day; and Minute, which shows the minutes during which the guard was asleep within the midnight hour. (The Minute column's header shows the minute's ten's digit in the first row and the one's digit in the second row.) Awake is shown as ., and asleep is shown as #.
# Note that guards count as asleep on the minute they fall asleep, and they count as awake on the minute they wake up. For example, because Guard #10 wakes up at 00:25 on 1518-11-01, minute 25 is marked as awake.
# If you can figure out the guard most likely to be asleep at a specific time, you might be able to trick that guard into working tonight so you can have the best chance of sneaking in. You have two strategies for choosing the best guard/minute combination.
# Strategy 1: Find the guard that has the most minutes asleep. What minute does that guard spend asleep the most?
# In the example above, Guard #10 spent the most minutes asleep, a total of 50 minutes (20+25+5), while Guard #99 only slept for a total of 30 minutes (10+10+10). Guard #10 was asleep most during minute 24 (on two days, whereas any other minute the guard was asleep was only seen on one day).
# While this example listed the entries in chronological order, your entries are in the order you found them. You'll need to organize them before they can be analyzed.
# What is the ID of the guard you chose multiplied by the minute you chose? (In the above example, the answer would be 10 * 24 = 240.)
def parse_line(line, hash)
parts = line.split(']')
ts = parts[0][1..-1]
text = parts[1].strip
dt = Time.parse(ts)
puts "#{dt} #{text}"
hash[dt] = {
'text' => text
}
end
def read_input(file_name)
all_inputs = Hash.new
file = File.open(file_name)
input_data = file.read
input_data.each_line do |line|
#next if line.start_with?('#')
#next if line.chomp.empty?
input = line.chomp.strip
parse_line(input, all_inputs)
end
return all_inputs
end
def guard_init(guards, id)
return if guards.key?(id)
guards[id] = {
'id' => id,
'total' => 0,
'min' => Hash.new
}
end
def guard_update(guards, id, t_start, t_end)
guards[id]['total'] += t_end - t_start
t_start.upto(t_end-1) do |min|
if guards[id]['min'].key?(min)
guards[id]['min'][min] += 1
else
guards[id]['min'][min] = 1
end
end
end
def brute_force(file_name)
inputs = read_input(file_name)
puts "Read #{inputs.length} lines"
#pp inputs
#puts "*"*20
sorted_inputs = inputs.sort.to_h
pp sorted_inputs
guards = Hash.new
id = 0
t_start = 0
t_end = 0
sorted_inputs.each do |key,record|
#puts record['text']
match = /.*\#(\d*) begins shift/.match(record['text'])
if match
id = match[1]
puts "#{id} start"
guard_init(guards, id)
elsif 'falls asleep' == record['text']
puts " #{id} sleep"
t_start = key.min
elsif 'wakes up' == record['text']
puts " #{id} wake"
t_end = key.min
puts " #{id} slept s=#{t_start} e=#{t_end}"
guard_update(guards, id, t_start, t_end)
end
end
#pp guards
# part 1 answer.
#
# Sort guards by total minute slept to find guard who slept the most
sorted_guards = guards.sort_by {|_key, value| value['total']}.reverse
#pp sorted_guards
# Now sort minutes slept by guard and take first one which is most
# minutes slept by that guard
guard = sorted_guards.first[1]
pp guard
sorted_min = guard['min'].sort_by {|_key, value| value}.reverse
# Multiply guard id by minute to get answer to submit
id_min = guard['id'].to_i * sorted_min.first[0]
puts "#{guard['id']} * #{sorted_min.first[0]}(#{sorted_min.first[1]}) = #{id_min}"
puts ""
# part 2 answer
#
guards.each do |key, guard|
sorted_min = guard['min'].sort_by {|_key, value| value}
begin
guard['max_min'] = sorted_min.last[0]
guard['max_min_val'] = sorted_min.last[1]
rescue
puts "exception #{sorted_min}"
pp guard
guard['max_min'] = 0
guard['max_min_val'] = 0
end
end
sorted_guards_by_max_min = guards.sort_by {|_key, value| value['max_min_val']}
guard = sorted_guards_by_max_min.last[1]
id_max_min = guard['id'].to_i * guard['max_min'].to_i
puts "#{guard['id']} * #{guard['max_min']}(#{guard['max_min_val']}) = #{id_max_min}"
end
brute_force('sample.txt')
brute_force('aoc_04_2018_input.txt')
|
require 'rails_helper'
RSpec.describe SearchController, type: :controller do
describe "GET #result" do
context 'valid request' do
let(:questions) { create_list(:question, 2) }
before do
allow(Services::Search).to receive(:call).and_return(questions)
end
it 'assigns result of calling Services::Search to @result' do
get :result, params: {query: 'Text', query_object: 'all', page: '1', per_page: '20' }
expect(assigns(:result)).to eq questions
end
it "returns http success" do
get :result, params: {query: 'Text', query_object: 'all', page: '1', per_page: '20' }
expect(response).to have_http_status(:success)
end
it "renders :result template" do
get :result, params: {query: 'Text', query_object: 'all', page: '1', per_page: '20' }
expect(response).to render_template :result
end
end
context 'invalid request' do
it 'redirects to root_path' do
get :result, params: {query: 'test', query_object: '', page: '1', per_page: '20' }
expect(response).to redirect_to root_path
end
it "set flash alert" do
get :result, params: {query: '', query_object: 'all', page: '1', per_page: '20' }
expect(controller).to set_flash[:alert].to 'Empty query'
end
end
end
end
|
class Author < ApplicationRecord
has_and_belongs_to_many :packages
end
|
# class documentation here
class BenefitsController < ApplicationController
load_and_authorize_resource
skip_before_filter :verify_authenticity_token
before_filter :authenticate_user!
def index
@benefits = Benefit.all.order('threshold')
end
def generate_coupon
@benefit = Benefit.find(params[:id])
if current_user.enought_monthly_points?(@benefit.threshold)
create_coupon(@benefit.threshold, @config.multiple_speed_offer)
elsif current_user.loyalty_points >= @benefit.threshold
create_coupon(@benefit.threshold, 1)
end
redirect_to benefits_path
end
def create_coupon(threshold, multiple)
@coupon = Coupon.new
current_user.use_loyalty_points(threshold)
@coupon.update_attributes(user_id: current_user.id, status: 'nonutilise',
code: @coupon.generate_number,
benefit_type_id: @benefit.benefit_type_id,
price_cents: (@benefit.price_cents * multiple),
time_limit: Time.zone.now + @benefit.date_limit)
Emailer.send_coupon_email(@coupon, current_user).deliver
flash[:success] = "Votre coupon a été généré avec succés,
un mail viens de vous être envoyé avec le code de celui-ci"
end
def check_coupon
@coupon = current_user.coupons.find_by_code(params[:coupon])
flash[:error_coupon] = coupon_error_message(@coupon) if params[:coupon]
if @coupon.present? && @coupon.status == 'nonutilise'
flash[:success_coupon] = "Bravo vous êtes sur le point
de bénéficier de #{@coupon.price} € de réduction!"
end
end
private
def coupon_error_message(coupon)
if @coupon.present?
case coupon.status
when 'expire' then "Ce code est expiré."
when 'utilise' then "Ce code de promotion a déjà été utilisé"
end
else
'Ce code de promotion est inconnue'
end
end
end |
# encoding: utf-8
$:.unshift File.expand_path('../lib', __FILE__)
require 'i18n-env-var-lookup/version'
Gem::Specification.new do |s|
s.name = "i18n-env-var-lookup"
s.version = I18n::EnvVarLookup::VERSION
s.authors = ["Stayman Hou"]
s.email = ["stayman.hou@gmail.com"]
s.homepage = "https://github.com/StaymanHou/i18n-env-var-lookup"
s.summary = "Provides a backend to the i18n gem to allow translation definitions to reference environment variables"
s.description = "Provides a backend to the i18n gem to allow a definition to contain embedded references to environment variables by introducing the special embedded notation ~{}. E.g. {title: ~{APP_NAME}} will evaluate t(:title) to the value of the $APP_NAME environment variable."
s.files = `git ls-files app lib`.split("\n")
s.platform = Gem::Platform::RUBY
s.require_paths = ['lib']
s.rubyforge_project = '[none]'
s.add_dependency 'i18n'
s.add_dependency 'activesupport'
s.add_development_dependency 'rake'
s.add_development_dependency 'mocha'
s.add_development_dependency 'test_declarative'
s.add_development_dependency 'test-unit'
end
|
require 'rails_helper'
describe MenuItem, type: :model do
let(:menu_item) { build(:menu_item) }
describe 'associations' do
it { should have_many(:menus) }
end
describe 'validation' do
it 'should validate name' do
end
it 'should validate description'
it 'should have a user'
it 'should validate unique names in the scope of its user'
end
end
|
require "test_helper"
describe TasksController do
let (:task) {
Task.create name: "sample task", description: "this is an example for a test",
completion_date: Time.now + 5.days
}
# Tests for Wave 1
describe "index" do
it "can get the index path" do
# Act
get tasks_path
# Assert
must_respond_with :success
end
it "can get the root path" do
# Act
get root_path
# Assert
must_respond_with :success
end
end
# Unskip these tests for Wave 2
describe "show" do
it "can get a valid task" do
# Act
get task_path(task.id)
# Assert
must_respond_with :success
end
it "will redirect for an invalid task" do
# Act
get task_path(-1)
# Assert
must_respond_with :redirect
expect(flash[:error]).must_equal "Could not find task with id: -1"
end
end
describe "new" do
it "can get the new task page" do
# Act
get new_task_path
# Assert
must_respond_with :success
end
end
describe "create" do
it "can create a new task" do
# Arrange
task_hash = {
task: {
name: "new task",
description: "new task description",
completion_date: nil,
},
}
# Act-Assert
expect {
post tasks_path, params: task_hash
}.must_change "Task.count", 1
new_task = Task.find_by(name: task_hash[:task][:name])
expect(new_task.description).must_equal task_hash[:task][:description]
expect(new_task.completion_date).must_equal task_hash[:task][:completion_date]
must_respond_with :redirect
must_redirect_to task_path(new_task.id)
end
end
describe "edit" do
it "can get the edit page for an existing task" do
# Act
get edit_task_path(task.id)
# Assert
must_respond_with :success
end
it "will respond with redirect when attempting to edit a nonexistant task" do
# Act
get edit_task_path(-1)
# Assert
must_respond_with :redirect
expect(flash[:error]).must_equal "Could not find task with id: -1"
end
end
# Uncomment and complete these tests for Wave 3
describe "update" do
# Note: If there was a way to fail to save the changes to a task, that would be a great
# thing to test.
it "can update an existing task" do
# Arrange
test_id = Task.last.id
task_hash = {
task: {
name: "updated task",
description: "updated task description",
},
}
expect {
patch task_path(test_id), params: task_hash
}.wont_change "Task.count"
updated_task = Task.find_by(name: task_hash[:task][:name])
expect(updated_task.description).must_equal task_hash[:task][:description]
must_respond_with :redirect
must_redirect_to task_path(test_id)
end
it "will redirect to the root page if given an invalid id" do
# Act
patch task_path(-1)
# Assert
must_respond_with :redirect
expect(flash[:error]).must_equal "Could not find task with id: -1"
must_redirect_to root_path
end
end
# Complete these tests for Wave 4
describe "destroy" do
it "removes the test from the database" do
# Arrange
test_id = Task.last.id
# Act
expect {
delete task_path(test_id)
}.must_change "Task.count", -1
# Assert
expect(Task.find_by(id: test_id)).must_equal nil
must_respond_with :redirect
must_redirect_to root_path
end
it "redirects to root if the book does not exist" do
# Arrange
test_id = -1
# Act
delete task_path(test_id)
# Assert
must_respond_with :redirect
expect(flash[:error]).must_equal "Could not find task with id: -1"
must_redirect_to root_path
end
end
# Complete for Wave 4
describe "toggle_complete" do
it "can mark an incomplete task complete without changing anything else" do
# Arrange
test_task = Task.last
test_task.update completion_date: nil
initial_attributes = test_task.attributes.clone
task_hash = {
task: {
completion_date: Time.now.to_date,
},
}
#Act-Assert
expect {
patch toggle_complete_task_path(test_task.id), params: task_hash
}.wont_change "Task.count"
test_task.reload
# Completion date should change, but nothing else should.
expect(test_task.name).must_equal initial_attributes["name"]
expect(test_task.description).must_equal initial_attributes["description"]
expect(test_task.completion_date).must_equal task_hash[:task][:completion_date]
must_respond_with :redirect
must_redirect_to root_path
end
it "can mark a completed task as incomplete without changing anything else" do
# Arrange
test_task = Task.last
initial_attributes = test_task.attributes.clone
task_hash = {
task: {
completion_date: nil,
},
}
#Act-Assert
expect {
patch toggle_complete_task_path(test_task.id), params: task_hash
}.wont_change "Task.count"
test_task.reload
# Completion date should change, but nothing else should.
expect(test_task.name).must_equal initial_attributes["name"]
expect(test_task.description).must_equal initial_attributes["description"]
expect(test_task.completion_date).must_equal task_hash[:task][:completion_date]
expect(test_task.completion_date).must_be_nil
must_respond_with :redirect
must_redirect_to root_path
end
it "will redirect to the root page if given an invalid id" do
# Act
patch task_path(-1)
# Assert
must_respond_with :redirect
expect(flash[:error]).must_equal "Could not find task with id: -1"
must_redirect_to root_path
end
end
end
|
class Message < ActiveRecord::Base
belongs_to :user
validates :message, presence: true, length: { maximum: 100 }
end
|
class VesselSpecificationsController < ApplicationController
breadcrumb "Vessel Specifications", :vessel_specifications_path, match: :exact
before_action :get_vessel_specification, except: [:index, :new, :create]
def index
@vessel_specifications = VesselSpecification.paginate(page: params[:page], per_page: 15)
end
def show
breadcrumb @vessel_specification.vessel_name, vessel_specification_path(@vessel_specification)
end
def new
head(404) and return unless can?(current_user, :create)
breadcrumb "New Vessel Specification", new_vessel_specification_path
@vessel_specification = VesselSpecification.new
end
def edit
head(404) and return unless can?(current_user, :edit)
breadcrumb @vessel_specification.vessel_name, vessel_specification_path(@vessel_specification), match: :exact
breadcrumb 'Edit', edit_vessel_specification_path(@vessel_specification)
end
def create
head(404) and return unless can?(current_user, :create)
@vessel_specification = VesselSpecification.new(vessel_specification_params)
respond_to do |format|
if @vessel_specification.save
format.html {redirect_to @vessel_specification, flash: {success: 'Vessel Specification Created Successfully'}}
else
format.json {render json: @vessel_specification.errors, status: :unprocessable_entity}
end
end
end
def update
head(404) and return unless can?(current_user, :edit)
respond_to do |format|
if @vessel_specification.update(vessel_specification_params)
format.html {redirect_to @vessel_specification, flash: {success: 'Vessel Specification Updated Successfully'}}
else
format.json {render json: @vessel_specification.errors, status: :unprocessable_entity}
end
end
end
def destroy
head(404) and return unless can?(current_user, :destroy)
@vessel_specification.destroy
respond_to do |format|
format.html {redirect_to vessel_specifications_url, notice: 'Vessel Specification was successfully destroyed.'}
format.json {head :ok}
end
end
private
def vessel_specification_params
params.require(:vessel_specification).permit(:vessel_name, :ex_name, :status, :tracked, :deck_space, :crane_capacity, :dp_classification, :year_built, :accommodation_id, :imo, :primary_type, :detailed_type, :dive_system, :dive_system_bell, :dive_system_capacity, :dive_system_type, :rovs, :gross_tonnage, :length_overall_breadth, :flag_state, :mmsi, :deadweight, :web_scraper_url, :source, :record_update_log)
end
def get_vessel_specification
@vessel_specification = VesselSpecification.find(params[:id])
end
end
|
set :version, "staging"
# If you aren't deploying to /u/apps/#{application} on the target
# servers (which is the default), you can specify the actual location
# via the :deploy_to variable:
set :deploy_to, "/web/staging/#{application}"
set :shared_path, "/web/staging/#{application}/shared"
task :reset_staging_db, :roles => :db do
if version == "staging"
# put the app into maintenance mode
disable_web
# dump the production db into the staging db
run "mysqladmin -u subroot -p#{subroot_pass} -f drop staging_#{application}_prod"
run "mysqladmin -u subroot -p#{subroot_pass} create staging_#{application}_prod"
run "mysqldump -u subroot -p#{subroot_pass} --lock-tables=false --add-drop-table --quick --extended-insert production_#{application}_prod | mysql -u #{application} -p#{application} staging_#{application}_prod"
# put app into running mode
enable_web
puts "You might want to run cap reset_staging_db on any DIYs that are configured to point to the staging SDS so that the database ids will match up correctly."
else
puts "You have to run in staging to execute this task."
end
end
namespace :deploy do
#############################################################
# Passenger
#############################################################
# Restart passenger on deploy
desc "Restarting passenger with restart.txt"
task :restart, :roles => :app, :except => { :no_release => true } do
sudo "touch #{current_path}/tmp/restart.txt"
end
[:start, :stop].each do |t|
desc "#{t} task is a no-op with passenger"
task t, :roles => :app do ; end
end
end |
module IContact
class Subscription
include IContact::Model
key_attribute :subscription_id
attribute :contact_id, :type => Integer
attribute :list_id, :type => Integer
attribute :status, :type => String
end
end
|
class MailingsController < ApplicationController
before_action :normalize_params, only: [:create, :update]
before_action :set_mailings, only: :index
before_action :set_mailing, except: :index
load_and_authorize_resource
def create
if @mailing.save
redirect_to @mailing, notice: 'Mailing was successfully created.'
else
render action: :new
end
end
def update
if @mailing.update_attributes(mailing_params)
redirect_to @mailing, notice: 'Mailing was successfully updated.'
else
render action: :edit
end
end
def destroy
@mailing.destroy
redirect_to mailings_url
end
def index
authorize! :read, :mailing
end
def show
authorize! :read, :mailing
end
private
def set_mailings
@mailings = Mailing.order('id DESC').page(params[:page])
end
def set_mailing
@mailing = params[:id] ? Mailing.find(params[:id]) : Mailing.new(mailing_params)
end
def normalize_params
params[:mailing][:to] = params[:mailing][:to].select(&:present?)
end
def mailing_params
if params[:mailing]
self.params.require(:mailing)
.permit(:group, :from, :cc, :bcc, :subject, :body, to: [], seasons: [])
else
{ from: ENV['EMAIL_FROM'], to: 'teams', seasons: [Season.current.name] }
end
end
end
|
require 'sinatra/base'
require 'config_env'
require 'rack/ssl-enforcer'
require 'httparty'
require 'ap'
require 'concurrent'
require 'rbnacl/libsodium'
require 'json'
require 'jwt'
configure :development, :test do
require 'hirb'
Hirb.enable
absolute_path = File.absolute_path './config/config_env.rb'
ConfigEnv.path_to_config(absolute_path)
end
# Visualizations for Canvas LMS Classes
class CanvasVisualizationAPI < Sinatra::Base
enable :logging
use Rack::MethodOverride
configure :production do
use Rack::SslEnforcer
set :session_secret, ENV['MSG_KEY']
end
set :public_folder, File.expand_path('../../../public', __FILE__)
api_get_root = lambda do
"Welcome to our API v1. Here's <a "\
'href="https://github.com/ISS-Analytics/canvas-lms-visualizations-api">'\
'our github homepage</a>. To see how all our routes work, go to '\
'<a href="/api/v1/routes">/api/v1/routes</a>.'
end
api_routes_explained = lambda do
redirect '/swagger.html'
end
['/', '/api/v1/?'].each { |path| get path, &api_get_root }
get '/api/v1/routes', &api_routes_explained
end
|
class AccountsController < ApplicationController
# require login before letting someone access their account (duh)
# excluding logout so that if somehow, someone is directed to the logout
# link, but is, in fact, NOT logged in, they won't be prompted to log in just
# so that they can log out.
if Rails.env.production?
before_action :require_login, except: [:logout]
end
before_action :require_administrator, only: [:index]
before_action :initialize_uniqname
helper_method :total_overdue
helper_method :total_on_time
helper_method :total_checkouts
def index
# TODO
render inline: '<p>Not implemented</p>', layout: true
end
def show
# if a uniqname is specified, and the user loading the page is an
# administrator, allow them to view another person's account; if they're
# not an administrator, show them a 401 Unauthorized message; if no
# uniqname is specified, simply show the user's account
@overdue = Record.where(borrower: @uniqname).overdue
@out = Record.where(borrower: @uniqname).out_but_not_overdue
@total_checked_out = @overdue.length + @out.length
@pie_chart_params = {}
@pie_chart_params["Checked Out"] = @total_checked_out if (@total_checked_out > 0)
@pie_chart_params["Returned On Time"] = total_on_time if total_on_time > 0
@pie_chart_params["Returned Past Due"] = total_overdue if total_overdue > 0
end
def history
@records = Record.where(borrower: @uniqname).reorder(out: :desc)
end
def statistics
# generate a hash of 'title name' => 'number of checkouts' pairs for use in
# a pretty nifty pie chart
@common_titles = Hash[Record.where(borrower: @uniqname).group(:title_id).count.map { |k, v| [Title.find(k).name, v] }]
end
def logout
cookies.delete request.env["COSIGN_SERVICE"]
redirect_to Rails.configuration.cosign_logout_path
end
#############################################################################
private #####################################################################
#############################################################################
# private
def total_overdue
# NOT DATABASE AGNOSTIC
# DEPENDS UPON MYSQL FOR THE ` QUOTING OF COLUMN NAMES
# BECAUSE I'M LAZY
Record.where(borrower: @uniqname)
.where('(`in` > `due`) OR (? > `due` AND `in` IS NULL)', DateTime.now)
.length
end
# private
def total_on_time
# NOT DATABASE AGNOSTIC
# DEPENDS UPON MYSQL FOR THE ` QUOTING OF COLUMN NAMES
# BECAUSE I'M LAZY
# only includes records that are checked in
Record.where(borrower: @uniqname)
.where('(`in` <= `due`)', DateTime.now)
.length
end
# private
def total_checkouts
Record.where(borrower: @uniqname).length
end
# private
def initialize_uniqname
if params[:uniqname].nil? or params[:uniqname] == uniqname
# if no uniqname is passed, just present the user with their own account
# if the uniqname is passed, and it matches the uniqname of the user
# making the request, that's okay too
@uniqname = uniqname
else
if administrator?
# only administrators are allowed to view other peoples accounts
@uniqname = params[:uniqname]
else
# if not an administrator, they're not allowed to view other people's accounts
redirect_to unauthorized_path
return
end
end
end
end
|
Rails.application.routes.draw do
# For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html
root 'welcome#landing_page'
get '/courses/cheapest', to: 'courses#cheapest'
get '/login', to: 'sessions#new'
post '/login', to: 'sessions#create'
post '/logout', to: 'sessions#destroy'
resources :users do
resources :courses, only: [:index]
end
resources :courses do
resources :reviews, only: [:new]
end
resources :reviews
get 'auth/:provider/callback' => 'sessions#omniauth'
end
|
#
# Copyright 2009 Huygens Instituut for the History of the Netherlands, Den Haag, The Netherlands.
#
# This file is part of New Women Writers.
#
# New Women Writers is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# New Women Writers is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with New Women Writers. If not, see <http://www.gnu.org/licenses/>.
#
# Settings specified here will take precedence over those in config/environment.rb
# In the development environment your application's code is reloaded on
# every request. This slows down response time but is perfect for development
# since you don't have to restart the webserver when you make code changes.
config.cache_classes = false
# Log error messages when you accidentally call methods on nil.
config.whiny_nils = true
# Show full error reports and disable caching
config.action_controller.consider_all_requests_local = true
config.action_view.debug_rjs = true
config.action_controller.perform_caching = false
# Don't care if the mailer can't send
config.action_mailer.raise_delivery_errors = false |
require 'spec_helper'
describe CsvRowModel::Model::Header do
let(:instance) { described_class.new(:string1, row_model_class, string1: "context") }
let(:row_model_class) do
Class.new(BasicRowModel) do
def self.format_header(*args); args.join("__") end
end
end
describe "#value" do
subject { instance.value }
it "returns the formatted_header" do
expect(subject).to eql "string1__#<OpenStruct string1=\"context\">"
end
context "with :header option" do
let(:row_model_class) do
Class.new(BasicRowModel) do
merge_options :string1, header: "waka"
end
end
it "returns the option value" do
expect(subject).to eql "waka"
end
end
end
end |
require 'rails_helper'
RSpec.describe Role, type: :model do
it { is_expected.to have_and_belong_to_many(:users) }
it { is_expected.to validate_presence_of(:name) }
it { is_expected.to validate_uniqueness_of(:name) }
it { is_expected.to validate_presence_of(:url_slug) }
it { is_expected.to validate_uniqueness_of(:url_slug) }
it { is_expected.to have_db_column(:name).of_type(:string) }
it { is_expected.to have_db_column(:displayable).of_type(:boolean) }
it { is_expected.to have_db_column(:description).of_type(:text) }
it { is_expected.to validate_presence_of(:url_slug) }
it { is_expected.to validate_uniqueness_of(:url_slug) }
it { is_expected.to have_db_column(:created_at).of_type(:datetime) }
it { is_expected.to have_db_column(:updated_at).of_type(:datetime) }
end
|
module IControl::GlobalLB
##
# The PoolMember interface enables you to work with the pool members and their settings,
# and statistics.
class PoolMember < IControl::Base
set_id_name "pool_names"
class MemberDependency < IControl::Base::Struct; end
class MemberEnabledState < IControl::Base::Struct; end
class MemberMetricLimit < IControl::Base::Struct; end
class MemberMonitorAssociation < IControl::Base::Struct; end
class MemberMonitorAssociationRemoval < IControl::Base::Struct; end
class MemberObjectStatus < IControl::Base::Struct; end
class MemberOrder < IControl::Base::Struct; end
class MemberRatio < IControl::Base::Struct; end
class MemberStatisticEntry < IControl::Base::Struct; end
class MemberStatistics < IControl::Base::Struct; end
class MemberDependencySequence < IControl::Base::Sequence ; end
class MemberDependencySequenceSequence < IControl::Base::SequenceSequence ; end
class MemberEnabledStateSequence < IControl::Base::Sequence ; end
class MemberEnabledStateSequenceSequence < IControl::Base::SequenceSequence ; end
class MemberMetricLimitSequence < IControl::Base::Sequence ; end
class MemberMetricLimitSequenceSequence < IControl::Base::SequenceSequence ; end
class MemberMonitorAssociationRemovalSequence < IControl::Base::Sequence ; end
class MemberMonitorAssociationRemovalSequenceSequence < IControl::Base::SequenceSequence ; end
class MemberMonitorAssociationSequence < IControl::Base::Sequence ; end
class MemberMonitorAssociationSequenceSequence < IControl::Base::SequenceSequence ; end
class MemberObjectStatusSequence < IControl::Base::Sequence ; end
class MemberObjectStatusSequenceSequence < IControl::Base::SequenceSequence ; end
class MemberOrderSequence < IControl::Base::Sequence ; end
class MemberOrderSequenceSequence < IControl::Base::SequenceSequence ; end
class MemberRatioSequence < IControl::Base::Sequence ; end
class MemberRatioSequenceSequence < IControl::Base::SequenceSequence ; end
class MemberStatisticEntrySequence < IControl::Base::Sequence ; end
class MemberStatisticsSequence < IControl::Base::Sequence ; end ##
# Adds the virtual servers to the dependency list that this pool members depend on.
# @rspec_example
# @raise [IControl::IControl::Common::AccessDenied] raised if the client credentials are not valid.
# @raise [IControl::IControl::Common::InvalidArgument] raised if one of the arguments is invalid.
# @raise [IControl::IControl::Common::OperationFailed] raised if an operation error occurs.
# @param [Hash] opts
# @option opts [IControl::GlobalLB::PoolMember::MemberDependency[]] :dependencies The dependency list of VSes that the specified pool members depend on.
def add_dependency(opts)
opts = check_params(opts,[:dependencies])
super(opts)
end
##
# Gets the statistics for all pool members of this pool.
# @rspec_example
# @return [MemberStatistics]
# @raise [IControl::IControl::Common::AccessDenied] raised if the client credentials are not valid.
# @raise [IControl::IControl::Common::InvalidArgument] raised if one of the arguments is invalid.
# @raise [IControl::IControl::Common::OperationFailed] raised if an operation error occurs.
def all_statistics
super
end
##
# Gets the list of virtual servers that this pool members depend on.
# @rspec_example
# @return [MemberDependency[]]
# @raise [IControl::IControl::Common::AccessDenied] raised if the client credentials are not valid.
# @raise [IControl::IControl::Common::InvalidArgument] raised if one of the arguments is invalid.
# @raise [IControl::IControl::Common::OperationFailed] raised if an operation error occurs.
# @param [Hash] opts
# @option opts [IControl::Common::IPPortDefinition[]] :members The pool members.
def dependency(opts)
opts = check_params(opts,[:members])
super(opts)
end
##
# Gets the enabled states for this members in this pool.
# @rspec_example
# @return [MemberEnabledState[]]
# @raise [IControl::IControl::Common::AccessDenied] raised if the client credentials are not valid.
# @raise [IControl::IControl::Common::InvalidArgument] raised if one of the arguments is invalid.
# @raise [IControl::IControl::Common::OperationFailed] raised if an operation error occurs.
# @param [Hash] opts
# @option opts [IControl::Common::IPPortDefinition[]] :members The pool members.
def enabled_state(opts)
opts = check_params(opts,[:members])
super(opts)
end
##
# Gets the metric limits for this members of this pool.
# @rspec_example
# @return [MemberMetricLimit[]]
# @raise [IControl::IControl::Common::AccessDenied] raised if the client credentials are not valid.
# @raise [IControl::IControl::Common::InvalidArgument] raised if one of the arguments is invalid.
# @raise [IControl::IControl::Common::OperationFailed] raised if an operation error occurs.
# @param [Hash] opts
# @option opts [IControl::Common::IPPortDefinition[]] :members The pool members.
def limit(opts)
opts = check_params(opts,[:members])
super(opts)
end
##
# Gets the monitor associations used by this pool members, i.e. the monitor rules used
# by the pool members.
# @rspec_example
# @return [MemberMonitorAssociation[]]
# @raise [IControl::IControl::Common::AccessDenied] raised if the client credentials are not valid.
# @raise [IControl::IControl::Common::InvalidArgument] raised if one of the arguments is invalid.
# @raise [IControl::IControl::Common::OperationFailed] raised if an operation error occurs.
def monitor_association
super
end
##
# Gets the statuses for this members in this pool.
# @rspec_example
# @return [MemberObjectStatus[]]
# @raise [IControl::IControl::Common::AccessDenied] raised if the client credentials are not valid.
# @raise [IControl::IControl::Common::InvalidArgument] raised if one of the arguments is invalid.
# @raise [IControl::IControl::Common::OperationFailed] raised if an operation error occurs.
# @param [Hash] opts
# @option opts [IControl::Common::IPPortDefinition[]] :members The pool members.
def object_status(opts)
opts = check_params(opts,[:members])
super(opts)
end
##
# Gets the orders for this members in this pool.
# @rspec_example
# @return [MemberOrder[]]
# @raise [IControl::IControl::Common::AccessDenied] raised if the client credentials are not valid.
# @raise [IControl::IControl::Common::InvalidArgument] raised if one of the arguments is invalid.
# @raise [IControl::IControl::Common::OperationFailed] raised if an operation error occurs.
# @param [Hash] opts
# @option opts [IControl::Common::IPPortDefinition[]] :members The pool members.
def order(opts)
opts = check_params(opts,[:members])
super(opts)
end
##
# Gets the ratios for this members in this pool.
# @rspec_example
# @return [MemberRatio[]]
# @raise [IControl::IControl::Common::AccessDenied] raised if the client credentials are not valid.
# @raise [IControl::IControl::Common::InvalidArgument] raised if one of the arguments is invalid.
# @raise [IControl::IControl::Common::OperationFailed] raised if an operation error occurs.
# @param [Hash] opts
# @option opts [IControl::Common::IPPortDefinition[]] :members The pool members.
def ratio(opts)
opts = check_params(opts,[:members])
super(opts)
end
##
# Gets the statistics for this set of pool members.
# @rspec_example
# @return [MemberStatistics]
# @raise [IControl::IControl::Common::AccessDenied] raised if the client credentials are not valid.
# @raise [IControl::IControl::Common::InvalidArgument] raised if one of the arguments is invalid.
# @raise [IControl::IControl::Common::OperationFailed] raised if an operation error occurs.
# @param [Hash] opts
# @option opts [IControl::Common::IPPortDefinition[]] :members The members to get statistics from.
def statistics(opts)
opts = check_params(opts,[:members])
super(opts)
end
##
# Gets the version information for this interface.
# @rspec_example
# @return [String]
def version
super
end
##
# Removes any and all dependencies of this pool members.
# @rspec_example
# @raise [IControl::IControl::Common::AccessDenied] raised if the client credentials are not valid.
# @raise [IControl::IControl::Common::InvalidArgument] raised if one of the arguments is invalid.
# @raise [IControl::IControl::Common::OperationFailed] raised if an operation error occurs.
# @param [Hash] opts
# @option opts [IControl::Common::IPPortDefinition[]] :members The pool members to remove the dependencies from. These pool members will no longer have any dependency on any other virtual servers.
def remove_all_dependencies(opts)
opts = check_params(opts,[:members])
super(opts)
end
##
# Removes the virtual servers from the dependency list that this pool members depend
# on.
# @rspec_example
# @raise [IControl::IControl::Common::AccessDenied] raised if the client credentials are not valid.
# @raise [IControl::IControl::Common::InvalidArgument] raised if one of the arguments is invalid.
# @raise [IControl::IControl::Common::OperationFailed] raised if an operation error occurs.
# @param [Hash] opts
# @option opts [IControl::GlobalLB::PoolMember::MemberDependency[]] :dependencies The dependency list of VSes that the specified pool members depend on.
def remove_dependency(opts)
opts = check_params(opts,[:dependencies])
super(opts)
end
##
# Removes the monitor associations for this pool members. Depending on the monitor
# association removal rule specified, this basically deletes any explicit monitor associations
# between a pool member and a monitor rule and thus causing the pool member to use
# the default monitor association of its parent pool, or this will delete any monitor
# association for the pool members altogether, i.e. this pool members will no longer
# be monitored.
# @rspec_example
# @raise [IControl::IControl::Common::AccessDenied] raised if the client credentials are not valid.
# @raise [IControl::IControl::Common::InvalidArgument] raised if one of the arguments is invalid.
# @raise [IControl::IControl::Common::OperationFailed] raised if an operation error occurs.
# @param [Hash] opts
# @option opts [IControl::GlobalLB::PoolMember::MemberMonitorAssociationRemoval[]] :monitor_associations The monitor association removal rules that will be used to remove the monitor associations for the specified pool members.
def remove_monitor_association(opts)
opts = check_params(opts,[:monitor_associations])
super(opts)
end
##
# Resets the statistics for this set of pool members.
# @rspec_example
# @raise [IControl::IControl::Common::AccessDenied] raised if the client credentials are not valid.
# @raise [IControl::IControl::Common::InvalidArgument] raised if one of the arguments is invalid.
# @raise [IControl::IControl::Common::OperationFailed] raised if an operation error occurs.
# @param [Hash] opts
# @option opts [IControl::Common::IPPortDefinition[]] :members The members to get statistics from.
def reset_statistics(opts)
opts = check_params(opts,[:members])
super(opts)
end
##
# Sets the enabled states for this pool members in this pool.
# @rspec_example
# @raise [IControl::IControl::Common::AccessDenied] raised if the client credentials are not valid.
# @raise [IControl::IControl::Common::InvalidArgument] raised if one of the arguments is invalid.
# @raise [IControl::IControl::Common::OperationFailed] raised if an operation error occurs.
# @param [Hash] opts
# @option opts [IControl::GlobalLB::PoolMember::MemberEnabledState[]] :states The members and the states to be set.
def set_enabled_state(opts)
opts = check_params(opts,[:states])
super(opts)
end
##
# Sets the metric limits for this members of this pool.
# @rspec_example
# @raise [IControl::IControl::Common::AccessDenied] raised if the client credentials are not valid.
# @raise [IControl::IControl::Common::InvalidArgument] raised if one of the arguments is invalid.
# @raise [IControl::IControl::Common::OperationFailed] raised if an operation error occurs.
# @param [Hash] opts
# @option opts [IControl::GlobalLB::PoolMember::MemberMetricLimit[]] :limits The pool members' metric limits.
def set_limit(opts)
opts = check_params(opts,[:limits])
super(opts)
end
##
# Sets/creates the monitor associations for this pool members. This basically creates
# the monitor associations between a pool member and a monitor rule.
# @rspec_example
# @raise [IControl::IControl::Common::AccessDenied] raised if the client credentials are not valid.
# @raise [IControl::IControl::Common::InvalidArgument] raised if one of the arguments is invalid.
# @raise [IControl::IControl::Common::OperationFailed] raised if an operation error occurs.
# @param [Hash] opts
# @option opts [IControl::GlobalLB::PoolMember::MemberMonitorAssociation[]] :monitor_associations The monitor associations that will be used to evaluate the specified pool members.
def set_monitor_association(opts)
opts = check_params(opts,[:monitor_associations])
super(opts)
end
##
# Sets the orders for this pool members.
# @rspec_example
# @raise [IControl::IControl::Common::AccessDenied] raised if the client credentials are not valid.
# @raise [IControl::IControl::Common::InvalidArgument] raised if one of the arguments is invalid.
# @raise [IControl::IControl::Common::OperationFailed] raised if an operation error occurs.
# @param [Hash] opts
# @option opts [IControl::GlobalLB::PoolMember::MemberOrder[]] :orders The members and the orders to be set.
def set_order(opts)
opts = check_params(opts,[:orders])
super(opts)
end
##
# Sets the ratios for this pool members.
# @rspec_example
# @raise [IControl::IControl::Common::AccessDenied] raised if the client credentials are not valid.
# @raise [IControl::IControl::Common::InvalidArgument] raised if one of the arguments is invalid.
# @raise [IControl::IControl::Common::OperationFailed] raised if an operation error occurs.
# @param [Hash] opts
# @option opts [IControl::GlobalLB::PoolMember::MemberRatio[]] :ratios The members and the ratios to be set.
def set_ratio(opts)
opts = check_params(opts,[:ratios])
super(opts)
end
##
# A struct that describes a pool member's dependencies on other virtual servers.
# @attr [IControl::Common::IPPortDefinition] member The IP address and port of the pool member.
# @attr [IControl::GlobalLB::VirtualServerDefinitionSequence] dependencies The list of virtual servers that this member depends on.
class MemberDependency < IControl::Base::Struct
icontrol_attribute :member, IControl::Common::IPPortDefinition
icontrol_attribute :dependencies, IControl::GlobalLB::VirtualServerDefinitionSequence
end
##
# A struct that describes a pool member state.
# @attr [IControl::Common::IPPortDefinition] member The IP address and port of the pool member.
# @attr [IControl::Common::EnabledState] state The state of the specified pool member.
class MemberEnabledState < IControl::Base::Struct
icontrol_attribute :member, IControl::Common::IPPortDefinition
icontrol_attribute :state, IControl::Common::EnabledState
end
##
# A struct that contains metric limits for a pool member.
# @attr [IControl::Common::IPPortDefinition] member The IP address and port of the pool member.
# @attr [IControl::GlobalLB::MetricLimitSequence] metric_limits Metric limits of the pool.
class MemberMetricLimit < IControl::Base::Struct
icontrol_attribute :member, IControl::Common::IPPortDefinition
icontrol_attribute :metric_limits, IControl::GlobalLB::MetricLimitSequence
end
##
# A struct that describes a pool member's monitor association.
# @attr [IControl::GlobalLB::MonitorIPPort] member The pool member definition with which the monitor rule is associated with.
# @attr [IControl::GlobalLB::MonitorRule] monitor_rule The monitor rule used in the monitor association.
class MemberMonitorAssociation < IControl::Base::Struct
icontrol_attribute :member, IControl::GlobalLB::MonitorIPPort
icontrol_attribute :monitor_rule, IControl::GlobalLB::MonitorRule
end
##
# A struct that describes a pool member's monitor association to be removed.
# @attr [IControl::GlobalLB::MonitorIPPort] member The pool member definition whose monitor association will be removed.
# @attr [IControl::GlobalLB::MonitorAssociationRemovalRule] removal_rule The rule indicating how the monitor association will be removed.
class MemberMonitorAssociationRemoval < IControl::Base::Struct
icontrol_attribute :member, IControl::GlobalLB::MonitorIPPort
icontrol_attribute :removal_rule, IControl::GlobalLB::MonitorAssociationRemovalRule
end
##
# A struct that describes a pool member status.
# @attr [IControl::Common::IPPortDefinition] member The IP address and port of the pool member.
# @attr [IControl::Common::ObjectStatus] status The status of the specified pool member.
class MemberObjectStatus < IControl::Base::Struct
icontrol_attribute :member, IControl::Common::IPPortDefinition
icontrol_attribute :status, IControl::Common::ObjectStatus
end
##
# A struct that describes a pool member order.
# @attr [IControl::Common::IPPortDefinition] member The IP address and port of the pool member.
# @attr [Numeric] order The order given to the specified pool member.
class MemberOrder < IControl::Base::Struct
icontrol_attribute :member, IControl::Common::IPPortDefinition
icontrol_attribute :order, Numeric
end
##
# A struct that describes a pool member ratio.
# @attr [IControl::Common::IPPortDefinition] member The IP address and port of the pool member.
# @attr [Numeric] ratio The ratio given to the specified pool member.
class MemberRatio < IControl::Base::Struct
icontrol_attribute :member, IControl::Common::IPPortDefinition
icontrol_attribute :ratio, Numeric
end
##
# A struct that describes statistics for a particular pool member.
# @attr [IControl::Common::IPPortDefinition] member The pool member definition.
# @attr [IControl::Common::StatisticSequence] statistics The statistics for the pool member.
class MemberStatisticEntry < IControl::Base::Struct
icontrol_attribute :member, IControl::Common::IPPortDefinition
icontrol_attribute :statistics, IControl::Common::StatisticSequence
end
##
# A struct that describes pool member statistics and timestamp.
# @attr [IControl::GlobalLB::PoolMember::MemberStatisticEntrySequence] statistics The statistics for a sequence of pool members.
# @attr [IControl::Common::TimeStamp] time_stamp The time stamp at the time the statistics are gathered.
class MemberStatistics < IControl::Base::Struct
icontrol_attribute :statistics, IControl::GlobalLB::PoolMember::MemberStatisticEntrySequence
icontrol_attribute :time_stamp, IControl::Common::TimeStamp
end
## A sequence of pool member dependency definitions.
class MemberDependencySequence < IControl::Base::Sequence ; end
## An alias for a sequence of pool member dependency definitions.
class MemberDependencySequenceSequence < IControl::Base::SequenceSequence ; end
## A sequence of pool member states.
class MemberEnabledStateSequence < IControl::Base::Sequence ; end
## An alias for a sequence of member states.
class MemberEnabledStateSequenceSequence < IControl::Base::SequenceSequence ; end
## A sequence of MemberMetricLimit's.
class MemberMetricLimitSequence < IControl::Base::Sequence ; end
## An alias for a sequence of MemberMetricLimit's.
class MemberMetricLimitSequenceSequence < IControl::Base::SequenceSequence ; end
## A sequence of MemberMonitorAssociationRemoval's.
class MemberMonitorAssociationRemovalSequence < IControl::Base::Sequence ; end
## An alias for a sequence of member MemberMonitorAssociationRemoval's.
class MemberMonitorAssociationRemovalSequenceSequence < IControl::Base::SequenceSequence ; end
## A sequence of monitor associations.
class MemberMonitorAssociationSequence < IControl::Base::Sequence ; end
## An alias for a sequence of member monitor associations.
class MemberMonitorAssociationSequenceSequence < IControl::Base::SequenceSequence ; end
## A sequence of pool member states.
class MemberObjectStatusSequence < IControl::Base::Sequence ; end
## An alias for a sequence of member statuses.
class MemberObjectStatusSequenceSequence < IControl::Base::SequenceSequence ; end
## A sequence of pool member orders.
class MemberOrderSequence < IControl::Base::Sequence ; end
## An alias for a sequence of member orders.
class MemberOrderSequenceSequence < IControl::Base::SequenceSequence ; end
## A sequence of pool member ratios.
class MemberRatioSequence < IControl::Base::Sequence ; end
## An alias for a sequence of member ratios.
class MemberRatioSequenceSequence < IControl::Base::SequenceSequence ; end
## A sequence of pool member statistics.
class MemberStatisticEntrySequence < IControl::Base::Sequence ; end
## An alias for a sequence of pool member statistics.
class MemberStatisticsSequence < IControl::Base::Sequence ; end
end
end
|
require 'rack'
module Hobbit
# The response object. See Rack::Response and Rack::Response::Helpers for
# more info:
# http://rack.rubyforge.org/doc/classes/Rack/Response.html
# http://rack.rubyforge.org/doc/classes/Rack/Response/Helpers.html
class Response < Rack::Response
def initialize(*)
super
headers['Content-Type'] ||= 'text/html; charset=utf-8'
end
end
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.