text stringlengths 10 2.61M |
|---|
class VideoProcessing
extend WithDatabaseConnection
@queue = :video
def self.perform app_session_id
start = Time.now
puts "AppSession[#{app_session_id}] is processing..."
app_session = AppSession.find app_session_id
touch = app_session.touch_track.download
screen = app_session.screen_track.download
rotation = app_session.orientation_track.rotation app_session.duration.to_i
if app_session.front_track
front_track = app_session.front_track
front = front_track.download
rotate_video front, rotation
front_track.upload front
end
unless app_session.event_track.nil?
event = app_session.event_track.download
importer = EventImporter.new(event)
importer.import(app_session)
end
gesture_converter = GestureConverter.new touch
gesture = gesture_converter.dump app_session.working_directory
processed = VideoProcessing.draw_touch screen, touch, rotation
thumbnail = VideoProcessing.thumbnail processed, rotation
app_session.destroy_presentation_track
app_session.destroy_gesture_track
presentation_track = PresentationTrack.new app_session: app_session
presentation_track.upload processed
presentation_track.thumbnail.upload thumbnail
gesture_track = GestureTrack.new app_session: app_session
gesture_track.upload gesture
if gesture_track.save && presentation_track.save
puts "AppSession[#{app_session_id}]: done processing in #{Time.now-start} s."
else
puts "AppSession[#{app_session_id}]: ERROR saving GestureTrack (#{gesture_track.valid?}) or PresentationTrack (#{presentation_track.valid?})"
end
# cleanup app_session.working_directory
end
def self.enqueue app_session_id
Resque.enqueue VideoProcessing, app_session_id
puts "AppSession[#{app_session_id}] is enqueued for VideoProcessing"
end
# TODO
def self.draw_touch screen_file, touch_file, rotation_angle
processed_filename = "#{screen_file.path}.draw_touch.mov"
`gesturedrawer -f "#{screen_file.path}" -p "#{touch_file.path}" -d "#{processed_filename}"`
rotate_video processed_filename, rotation_angle
VideoFile.new processed_filename
end
def self.rotate_video mp4_file, rotation_angle
`qtrotate.py "#{mp4_file}" "#{rotation_angle}"`
end
def self.thumbnail video_file, rotation_angle
dimension = "#{video_file.width}x#{video_file.height}"
thumbnail_filename = video_file.path+'.thumbnail.png'
transpose = case rotation_angle
when 90
"-vf transpose=1"
when 270
"-vf transpose=2"
when 180
"-vf vflip"
else
""
end
`ffmpeg -itsoffset 4 -i "#{video_file.path}" -vcodec png #{transpose} -vframes 1 -an -f rawvideo -s #{dimension} -y "#{thumbnail_filename}"`
File.new thumbnail_filename
end
def self.cleanup working_directory
FileUtils.remove_dir working_directory, true
end
end |
class User < ActiveRecord::Base
# Include default devise modules. Others available are:
# :token_authenticatable, :encryptable, :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :recoverable, :rememberable, :trackable, :validatable
# Setup accessible (or protected) attributes for your model
# attr_accessible :email, :password, :password_confirmation, :remember_me
attr_accessible :email, :password, :password_confirmation, :remember_me, :current_sign_in_ip, :role_id, :employee_id, :reset_password_token
#Record Associations
has_many :subjects
has_many :topics
has_many :forums
has_many :posts
has_many :jktests
has_many :testquestions
has_many :solvedtests
has_many :questions
belongs_to :role
#validation
validates_associated :testquestions
validates_associated :forums
validates_associated :posts
validates_associated :jktests
validates_associated :solvedtests
validates_associated :questions
validates :email, :uniqueness => true, :format => { :with => /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\Z/i,
:message => "Email not valide" }
validates :employee_id, :presence => true
#validates :role_id, :presence => true
before_validation :validate_role
before_destroy :delete_posts
def validate_role
errors.add(:role_id, 'Role not presence') if Role.find_by_id( self[:role_id] ) == nil
end
def delete_posts
Post.where("user_id = ? ",self[:id]).delete_all
end
end
|
module Treasury
module Fields
module Delayed
protected
# Internal: Отмена отложенных задач по приращению
#
# Returns Integer количество отмененных задач
def cancel_delayed_increments
Resque.remove_delayed_selection(Treasury::DelayedIncrementJob) do |args|
args[0]['field_class'] == field_model.field_class
end
end
end
end
end
|
# frozen_string_literal: true
# Create new card deck
require_relative 'card'
class Deck
attr_reader :deck, :suits, :ranks
def initialize
@deck = []
@suits = suits
@ranks = ranks
create_deck
end
def create_deck
card_generator = [(2..10).to_a, Card::PICTURES].flatten!
# puts "card_generator = #{card_generator}"
card_generator.each do |rank|
Card::SUITS.each do |suit|
@deck.push(Card.new(suit, rank))
end
end
end
end
|
class Solution < ActiveRecord::Base
belongs_to :health
belongs_to :student
end |
class CreateUserMessages < ActiveRecord::Migration
def change
create_table :user_messages, options: 'ENGINE=InnoDB, CHARSET=utf8' do |t|
# 用户系统消息收件箱
t.references :user # 关联用户
t.integer :m_type # 消息类型(群发消息或点对点消息)
t.integer :rel_id, :default => '0' # 关联的message的id
t.boolean :deleted, :default => '0' # 是否删除(0没有删除,1已经删除)
t.timestamps
end
add_index :user_messages, :user_id
add_index :user_messages, :rel_id
end
end
|
MESSAGE_URL = %r{^/discussions?/(?<discussion_id>[\w\d]{24})/messages?$}
MESSAGE_ID_URL = %r{^/discussions?/(?<discussion_id>[\w\d]{24})/messages?/(?<id>[\w\d]{24})$}
before "#{MESSAGE_URL}*" do
@entity_name = Message.name
end
[MESSAGE_URL, MESSAGE_ID_URL].each do |url|
before url do
@id = params[:id]
@discussion_id = params[:discussion_id]
@entity_name = Message.name
puts 'id = ' << @id.to_s
end
end
get MESSAGE_ID_URL do
discussion = Discussion.find_by_id @discussion_id
not_found_if_nil! discussion
message = Message.find_by_id @id
not_found_if_nil! message
ok message
end
get %r{/discussions?/(?<discussion_id>.+)/messages?} do
puts 'Search message'
ok do_search Message, params, {q: [:title], fields: [:course_id], }
end
post MESSAGE_URL do
discussion = Discussion.find_by_id @discussion_id
not_found_if_nil! discussion, @discussion_id
message = Message.new @json
message.discussion_id = discussion.id
message.save
created message
end
put MESSAGE_ID_URL do
discussion = Discussion.find_by_id @discussion_id
not_found_if_nil! discussion
message = Message.find_by_id @id
not_found_if_nil! message
[:id, :discussion_id].each { |field|
bad_request! if @json.has_key? field || message[field] != @json[field]
}
message = Message.update @id, @json
puts 'Update message: ' << message.inspect
ok message
end
delete MESSAGE_ID_URL do
discussion = Discussion.find_by_id @discussion_id
not_found_if_nil! discussion
message = Message.find_by_id @id
not_found_if_nil! message
Message.destroy @id
ok message
end
get %r{/messages?/(?:list|all)} do
puts 'Get all messages'
ok Message.all
end
|
class Video < ApplicationRecord
# belongs_to :user
has_many :reactions
validates :youtube_id, uniqueness: true
end
|
class Room
attr_accessor(:song_library, :guests_present, :entry_fee, :nightly_take)
attr_reader(:number, :guest_capacity)
def initialize(number)
@number = number
@song_library = []
@guests_present = []
@entry_fee = 15
@guest_capacity = 2
@nightly_take = 0
end
def add_song(song)
@song_library.push(song)
end
def remove_song(song)
@song_library.delete(song)
end
def check_in(guest)
if @guests_present.count < @guest_capacity
take_payment(guest)
@guests_present.push(guest)
check_playlist(guest)
else
return "Sorry, the room is full now"
end
end
def check_out(guest)
@guests_present.delete(guest)
end
def check_playlist(guest)
found_song = @song_library.find(){|song| song.title == guest.favourite_song}
if found_song
return "Whoo!" if found_song.title == guest.favourite_song
end
end
def take_payment(guest)
guest.money -= @entry_fee
@nightly_take += @entry_fee
end
end
|
class Comment < ActiveRecord::Base
belongs_to :post
validates_presence_of :name, :email, :comment
validates_format_of :email, :with => /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\Z/i, :on => :create
def website=(url)
prefix = ""
prefix = "http://" unless url.index("http://")
super prefix + url
end
end
|
class OrderItem < ActiveRecord::Base
belongs_to :order
belongs_to :product
validates :product_id, :order_id, presence: true
validates :quantity, numericality: { greater_than_or_equal_to: 0 }
def subtotal
quantity * self.product.price
end
end
|
class Playlist < ActiveRecord::Base
belongs_to :user
has_many :playlistings
has_many :songs, through: :playlistings
end
|
require "rails_helper"
RSpec.describe ConnectCallToVoicemail do
describe "#call" do
it "connects the participants of a call to voicemail" do
call = build_stubbed(:incoming_call, :with_participant)
adapter = spy(update_call: true)
result = described_class.new(
incoming_call: call,
adapter: adapter
).call
expect(result.success?).to be(true)
expect(adapter).to have_received(:update_call).with(hash_including(sid: call.from_sid))
end
it "returns a failure if the connection fails" do
call = spy
adapter = spy(update_call: false)
result = described_class.new(
incoming_call: call,
adapter: adapter
).call
expect(result.success?).to be(false)
end
end
end
|
require 'spec_helper'
resource "Chorus Views" do
let(:dataset) { datasets(:table) }
let(:owner) { users(:owner) }
let(:workspace) { workspaces(:public) }
let(:dataset_id) { dataset.id }
before do
log_in owner
end
post "/chorus_views" do
before do
any_instance_of(GpdbSchema) do |schema|
mock(schema).with_gpdb_connection.with_any_args
end
end
parameter :source_object_id, "Id of the source dataset/workfile"
parameter :source_object_type, "'dataset' or 'workfile'"
parameter :object_name, "Name of the Chorus View to be created"
parameter :schema_id, "Id of the schema to run the view in"
parameter :workspace_id, "Id of the workspace the Chorus View belongs to"
parameter :query, "SQL statement for the Chorus View, must start with SELECT or WITH"
required_parameters :source_object_id, :source_object_type, :object_name, :schema_id, :workspace_id, :query
let(:source_object_id) { dataset_id }
let(:source_object_type) { "dataset" }
let(:workspace_id) { workspace.id }
let(:object_name) {"MyChorusView"}
let(:schema_id) {workspace.sandbox.id}
let(:query) {"select 1;"}
example_request "Create a Chorus View" do
status.should == 201
end
end
put "/chorus_views/:id" do
before do
any_instance_of(GpdbSchema) do |schema|
mock(schema).with_gpdb_connection.with_any_args
end
end
parameter :id, "Id of the chorus view to update"
parameter :query, "New SQL statement for the Chorus View, must start with SELECT or WITH"
required_parameters :id, :query
let(:query) {"select 1;"}
let(:chorus_view) { datasets(:chorus_view) }
let(:id) { chorus_view.id }
example_request "Update a Chorus View" do
status.should == 200
end
end
delete "/chorus_views/:id" do
parameter :id, "Id of the chorus view to delete"
required_parameters :id
let(:chorus_view) { datasets(:chorus_view) }
let(:id) { chorus_view.id }
example_request "Delete a Chorus View" do
status.should == 200
end
end
post "/datasets/preview_sql" do
let(:sql_result) {
SqlResult.new.tap do |r|
r.add_column("t_bit", "bit")
r.add_rows([["10101"]])
r.schema = schema
end
}
before do
mock(SqlExecutor).execute_sql.with_any_args { sql_result }
end
parameter :schema_id, "Id of the schema to use for the SQL command"
parameter :query, "SQL to preview before creating a chorus view"
parameter :check_id, "A client-generated identifier which can be used to cancel this preview later"
required_parameters :schema_id, :query, :check_id
let(:schema) { gpdb_schemas(:default) }
let(:schema_id) { schema.id }
let(:query) { "SELECT * FROM table;" }
let(:check_id) {'0.43214321' }
example_request "Preview a Chorus View" do
status.should == 200
end
end
post "/chorus_views/:id/convert" do
let(:chorus_view) { datasets(:chorus_view) }
let(:id) { chorus_view.id }
let(:workspace_id) { workspace.id }
parameter :id, "Id of the chorus view to be converted"
parameter :workspace_id, "Id of workspace"
required_parameters :id, :workspace_id
before do
any_instance_of(ChorusView) do |view|
mock(view).convert_to_database_view.with_any_args
end
end
example_request "Convert a Chorus View to Database view" do
status.should == 201
end
end
end |
# == Schema Information
#
# Table name: file_sents
#
# id :bigint not null, primary key
# structure_id :bigint
# user_id :bigint
# content :text
# created_at :datetime not null
# updated_at :datetime not null
#
class FileSent < ApplicationRecord
belongs_to :structure
belongs_to :user
has_one_attached :file
end
|
class UserMailer < ApplicationMailer
def client_welcome_email(user, password='')
@user = user
@password = password
@url = url
@domain = domain_name
@locale = locale
I18n.with_locale(@locale) do
mail(
to: @user.email,
subject: I18n.translate('application_mailer.welcome_message.title')
)
end
end
def volunteer_welcome_email(user, password='')
@user = user
@password = password
@url = url
@domain = domain_name
@role = "volunteer"
@locale = locale
mail(to: @user.email, subject: 'Welcome to tutoría')
end
def new_message(user, sender, message)
@user, @sender, @message = user, sender, message
@url = url
I18n.with_locale(@user.locale) do
mail(
to: @user.email,
subject: "#{I18n.translate 'application_mailer.new_message.title'}: #{sender.first_name} - tutoría"
)
end
end
def account_deactivated(user)
@user = user
@admin_email = admin_email
mail(to: @user.email, subject: 'Tutoría Account Disabled')
end
def account_reactivated(user)
@user = user
@admin_email = admin_email
mail(to: @user.email, subject: 'Tutoría Account Re-enabled')
end
def account_activated(user)
@user = user
@admin_email = admin_email
mail(to: @user.email, subject: 'Please set your availabilities in tutoría')
end
def account_deleted(user)
@user = user
mail(to: @user.email, subject: 'Tutoría Account Deleted')
end
def password_updated(user)
@user = user
@admin_email = admin_email
mail(to: @user.email, subject: 'Tutoría Password Updated')
end
private
def domain_name
Rails.configuration.base_domain
end
def url
"#{domain_name}/#{@user.locale}/sign_in"
end
def admin_email
'admin@tutoria.io'
end
end
|
require 'spec_helper'
require 'project_razor/slice'
describe ProjectRazor::Slice do
# before :each do
# @test = TestClass.new
# @test.extend(ProjectRazor::SliceUtil::Common)
# # TODO: Review external dependencies here:
# @test.extend(ProjectRazor::Utility)
# end
context "code formerly known as SliceUtil::Common" do
describe "validate_arg" do
subject('slice') { ProjectRazor::Slice.new([]) }
it "should return false for empty values" do
[ nil, {}, '', '{}', '{1}', ['', 1], [nil, 1], ['{}', 1] ].each do |val|
slice.validate_arg(*[val].flatten).should == false
end
end
it "should return valid value" do
slice.validate_arg('foo','bar').should == ['foo', 'bar']
end
end
end
end
|
require File.expand_path(File.dirname(__FILE__) + "/my_sears_test_base")
describe "MySearsAdminReviewModerationTest" do
include MySearsTestBase
before(:all) do
setup_super_user
end
before(:each) do
setup_pages
@valid_product_info = create_new_product
end
#it "should verify removal of html tags from the in the moderation content", :pending => true do
# assert_equal @admin_moderation_page.review_description,"this is a sample text"
#end
it "should verify inclusion of TR as rejection code" do
@home_page.navigate_to_login
@login_popup.login @super_user
@product_reviews_page.open(@valid_product_info)
@product_reviews_page.click_on_review_it
@product_reviews_page.fill_the_mandatory_fields_to_complete_the_review
@product_reviews_page.enter_a_review_description_with_formating "this is a sample text"
@product_reviews_page.click_on_publish_button
assert_equal(true, @product_reviews_page.does_submit_review_successful_message_exists)
@admin_moderation_page.open_community_admin_home_page
@admin_moderation_page.click_on_review_moderation
@admin_moderation_page.search_reviews_by_user @super_user.screen_name
@admin_moderation_page.reject_first_review_with_tr_code
assert (Review.find(:all , :conditions => {:status => 'rejected'}).last.content_documents.first.reason_codes).include? "TR"
end
end
|
require "application_system_test_case"
class BeatsTest < ApplicationSystemTestCase
setup do
@beat = beats(:one)
end
test "visiting the index" do
visit beats_url
assert_selector "h1", text: "Beats"
end
test "creating a Beat" do
visit beats_url
click_on "New Beat"
fill_in "Price", with: @beat.price
fill_in "Scale", with: @beat.scale
fill_in "Tempo", with: @beat.tempo
fill_in "Title", with: @beat.title
click_on "Create Beat"
assert_text "Beat was successfully created"
click_on "Back"
end
test "updating a Beat" do
visit beats_url
click_on "Edit", match: :first
fill_in "Price", with: @beat.price
fill_in "Scale", with: @beat.scale
fill_in "Tempo", with: @beat.tempo
fill_in "Title", with: @beat.title
click_on "Update Beat"
assert_text "Beat was successfully updated"
click_on "Back"
end
test "destroying a Beat" do
visit beats_url
page.accept_confirm do
click_on "Destroy", match: :first
end
assert_text "Beat was successfully destroyed"
end
end
|
# encoding: UTF-8
RC = <<-EOT
EOT
class Film
class << self
def divisions_file
@divisions_file ||= File.join(folder, 'divisions.txt')
end
# Ouvrir le fichier contenant les divisions du film et
# les calcule si nécessaire (si le fichier n'existe pas.)
def open_file_divisions forcer = false
if forcer && File.exist?(divisions_file)
File.unlink divisions_file
end
File.exist?(divisions_file) || calcule_and_save_divisions
`mate "#{divisions_file}"`
end
# Calcule les divisions et les écrit dans un fichier
# `divisions.txt` placé dans le dossier de la collecte
def calcule_and_save_divisions
File.open(divisions_file,'wb'){|f| f.write divisions}
end
# Code de la collecte
def code_collecte
@code_collecte ||= STDIN.read
end
def debut_film
@debut_film ||= begin
if collecte_simple?
# En mode de collecte simple
# Dans ce mode, on prend la première horloge de
# scène qui se présente
code_collecte.match(/^([0-9]:[0-9][0-9]?:[0-9][0-9]?) /).to_a[1].strip
else
# En mode de collecte "complet"
code_collecte.match(/^SCENE:(.*)$/).to_a[1].strip
end
end
end
def fin_film
@fin_film ||= begin
if collecte_simple?
code_collecte.scan(/^([0-9]:[0-9][0-9]?:[0-9][0-9]?)/).to_a.last.first
else
code_collecte.match(/^FIN:(.*)$/).to_a[1].strip
end
end
end
# Méthode qui affiche en sortie les divisions logiques
# du film, pour l'établissement du paradigme de Field
# augmenté, notamment.
def divisions
@divisions ||= begin
cc = Array.new # Temps dans la collecte
ca = Array.new # Temps absolus
cc << "==== CALCUL DES POSITIONS DES DIVISIONS ===="
cc << "==== (temps dans la collecte) ===="
ca << "==== CALCUL DES POSITIONS DES DIVISIONS ===="
ca << "==== (temps absolus) ===="
duree = h2s(fin_film) - h2s(debut_film)
debut_secondes = h2s(debut_film)
cc << "\tDébut : #{debut_film}"
ca << "\tDébut : 0:00:00"
cc << "\tFin : #{fin_film}"
ca << "\tFin : #{s2h( h2s(fin_film) - debut_secondes)}"
cc << "\tDurée : #{s2h duree}"
ca << "\tDurée : #{s2h duree}"
# === les tiers ===
tiers = duree.to_f / 3
cc << "------------- Tiers ------------"
ca << "------------- Tiers ------------"
cc << "\t1/3 à #{s2h(tiers + debut_secondes)}"
ca << "\t1/3 à #{s2h(tiers)}"
cc << "\t2/3 à #{s2h(2*tiers + debut_secondes)}"
ca << "\t2/3 à #{s2h(2*tiers)}"
# ======= Quarts ===========
cc << "------------ Quarts ------------"
ca << "------------ Quarts ------------"
cc << "\t1/4 (développement) : #{s2h(duree/4 + debut_secondes)}"
ca << "\t1/4 (développement) : #{s2h(duree/4)}"
cc << "\t1/2 (clé de voûte) : #{s2h(duree / 2 + debut_secondes)}"
ca << "\t1/2 (clé de voûte) : #{s2h(duree / 2)}"
cc << "\t3/4 (dénouement) : #{s2h(3*duree/4 + debut_secondes)}"
ca << "\t3/4 (dénouement) : #{s2h(3*duree/4)}"
# === Cinquième ===
cinquieme = duree.to_f / 5
cc << "---------- Cinquièmes ---------"
ca << "---------- Cinquièmes ---------"
(1..5).each do |i|
cc << "\t#{i}/5 à #{s2h(i*cinquieme + debut_secondes)}"
ca << "\t#{i}/5 à #{s2h(i*cinquieme)}"
end
cc << "="*40
cc.join(RC) + RC*3 + ca.join(RC)
end
end
# ----------------------------------------------------
# Méthodes fonctionnelles
# ----------------------------------------------------
def h2s horloge
scs, mns, hrs = horloge.split(':').reverse
hrs.to_i * 3600 + mns.to_i * 60 + scs.to_i
end
def s2h secondes
s = secondes.to_i
hrs = s / 3600
mns = s % 3600
scs = (mns % 60).to_s.rjust(2,'0')
mns = (mns / 60).to_s.rjust(2,'0')
"#{hrs}:#{mns}:#{scs}"
end
end #/<< self
end #/Film
|
class ActivitiesController < ApplicationController
prepend_before_filter :authenticate!, only: [:new, :edit, :create, :update, :destroy]
# GET /activities
def index
@activities = Activity.all.order(day: :desc).includes(activity_comments: :game)
@activity_policy = Activity::Policy.new(current_user, nil)
set_content_ids
end
# GET /activities/1
def show
present Activity::Update
redirect_to_day_url && return
@activity_comment_form = ActivityComment::Create.present(params)
@activity_comment_policy = ActivityComment::Policy.new(current_user, @activity_comment_form.model)
set_item_id
end
# GET /activities/new
def new
form Activity::Create
end
# GET /activities/1/edit
def edit
form Activity::Update
end
# POST /activities
def create
run Activity::Create do |op|
return redirect_to(op.model, notice: 'Activity was successfully created.')
end
render :new
end
# PATCH/PUT /activities/1
def update
run Activity::Update do |op|
return redirect_to(op.model, notice: 'Activity was successfully updated.')
end
render :edit
end
# DELETE /activities/1
def destroy
run Activity::Destroy do |op|
return redirect_to(activities_path, notice: 'Activity was successfully destroyed.')
end
redirect_back(fallback_location: activity_path(params[:id]))
end
private
def set_item_id
set_content_ids(*@model.comments.map { |c| "activity_comment_#{c.id}" })
record_event_item_ids
end
def redirect_to_day_url
return if /\d{4}-\d{2}-\d{2}/ =~ params[:day]
redirect_to activity_path(day: @model.day)
end
end
|
class CustomersController < ApplicationController
before_action :set_customer, only: [:show, :edit, :update, :destroy]
before_action :set_company, only: [:index, :show, :new, :create, :edit, :update, :destroy]
def index
@customers = policy_scope(Customer).where(company_id: @company).sort
end
def show
@quotes = @customer.quotes
@bills = @customer.bills
authorize @customer
end
def new
@customer = Customer.new
authorize @customer
end
def create
@customer = Customer.new(customer_params)
@customer.company = @company
authorize @customer
if @customer.save
redirect_to company_customers_path(@company)
else
render :new
end
end
def edit
authorize @customer
end
def update
@customer.update(customer_params)
authorize @customer
if @customer.save
redirect_to company_customer_path(@company, @customer)
else
render :edit
end
end
def destroy
@customer.destroy
authorize @customer
redirect_to company_customers_path(@company)
end
private
def set_customer
@customer = Customer.find(params[:id])
end
def set_company
@company = Company.find(params[:company_id])
end
def customer_params
params.require(:customer).permit(:ref_client, :name, :address, :postcode, :city, :phone_1, :email_1, :phone_2, :email_2, :siren, :siret)
end
end
|
class Patient < ApplicationRecord
belongs_to :person
delegate :name, :cpf, :rg, :home_phone, :cell_phone, :birth_date, :sex, :to => :person
accepts_nested_attributes_for :person
end
|
module IControl::GlobalLB
##
# The Globals interface enables you to set and get global variables.
class Globals < IControl::Base
set_id_name "value"
##
# Gets the state to indicate whether local DNS servers that belong to AOL (America
# Online) are recognized.
# @rspec_example
# @return [EnabledState]
# @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 aol_aware_state
super
end
##
# Gets the state indicating whether to auto configure BIGIP/3DNS servers (automatic
# addition and deletion of self IPs and virtual servers.
# @rspec_example
# @return [EnabledState]
# @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 auto_configure_state
super
end
##
# Gets the state to indicate whether to autosync. Allows automatic updates of wideip.conf
# to/from other 3-DNSes.
# @rspec_example
# @return [EnabledState]
# @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 auto_sync_state
super
end
##
# Gets the state to indicate whether to cache LDNSes.
# @rspec_example
# @return [EnabledState]
# @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 cache_ldns_state
super
end
##
# Gets the state to indicate whether to check availability of a path before it uses
# the path for load balancing.
# @rspec_example
# @return [EnabledState]
# @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 check_dynamic_dependency_state
super
end
##
# Gets the state to indicate whether to check the availability of virtual servers.
# @rspec_example
# @return [EnabledState]
# @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 check_static_dependency_state
super
end
##
# Gets the default alternate LB method.
# @rspec_example
# @return [LBMethod]
# @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 default_alternate_lb_method
super
end
##
# Gets the default fallback LB method.
# @rspec_example
# @return [LBMethod]
# @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 default_fallback_lb_method
super
end
##
# Gets the default probe limit, the number of times to probe a path.
# @rspec_example
# @return [long]
# @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 default_probe_limit
super
end
##
# Gets the &quot;down_multiple" valu. If a host server or a host virtual server
# has been marked down for the last down_threshold probing cycles (timer_get_host_data
# or timer_get_vs_data respectively), then perform service checks every down_multiple
# * timer period instead.
# @rspec_example
# @return [long]
# @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 down_multiple
super
end
##
# Gets the &quot;down_threshold" valu. If a host server or a host virtual server
# has been marked down for the last down_threshold probing cycles (timer_get_host_data
# or timer_get_vs_data respectively), then perform service checks every down_multiple
# * timer period instead.
# @rspec_example
# @return [long]
# @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 down_threshold
super
end
##
# Gets the state to indicate whether persistent connections are allowed to remain connected,
# until TTL expires, when disabling a pool.
# @rspec_example
# @return [EnabledState]
# @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 drain_request_state
super
end
##
# Gets the state to indicate whether to dump the topology.
# @rspec_example
# @return [EnabledState]
# @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 dump_topology_state
super
end
##
# Gets the state to indicate whether to respect ACL.
# @rspec_example
# @return [EnabledState]
# @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 fb_respect_acl_state
super
end
##
# Gets the state to indicate whether to respect virtual server status when load balancing
# switches to the fallback mode.
# @rspec_example
# @return [EnabledState]
# @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 fb_respect_dependency_state
super
end
##
# Gets the number of seconds that an inactive LDNS remains cached.
# @rspec_example
# @return [long]
# @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 ldns_duration
super
end
##
# Gets the LDNS probe protocols. The order of the protocols in the sequence will be
# used to indicate the preferred protocols, i.e. the first protocol in the sequence
# is the most preferred protocol.
# @rspec_example
# @return [LDNSProbeProtocol]
# @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 ldns_probe_protocols
super
end
##
# Gets the link compensate inbound state. If set, the link allotment calculation will
# take into account traffic which does not flow through the BIGIP, i.e. if more traffic
# is flowing through a link as measured by SNMP on the router than is flowing through
# the BIGIP. This applies to inbound traffic which the major volume will initiate from
# internal clients.
# @rspec_example
# @return [EnabledState]
# @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 link_compensate_inbound_state
super
end
##
# Gets the link compensate outbound state. If set, the link allotment calculation will
# take into account traffic which does not flow through the BIGIP, i.e. if more traffic
# is flowing through a link as measured by SNMP on the router than is flowing through
# the BIGIP. This applies to outbound traffic which the major volume will initiate
# from internal clients.
# @rspec_example
# @return [EnabledState]
# @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 link_compensate_outbound_state
super
end
##
# Gets the link compensation history.
# @rspec_example
# @return [long]
# @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 link_compensation_history
super
end
##
# Gets the link limit factor, which is used to set a target percentage for traffic.
# For example, if it is set to 90, the ratio cost based load-balancing will set a ratio
# with a maximum valu equal to 90% of the limit valu for the link. Default is 95%.
# @rspec_example
# @return [long]
# @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 link_limit_factor
super
end
##
# Gets the link prepaid factor. Maximum percentage of traffic allocated to link which
# has a traffic allotment which has been prepaid. Default is 95%.
# @rspec_example
# @return [long]
# @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 link_prepaid_factor
super
end
##
# Gets the lower bound percentage column options in Internet Weather Map.
# @rspec_example
# @return [long]
# @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 lower_bound_percentage_column
super
end
##
# Gets the lower bound percentage row options in Internet Weather Map.
# @rspec_example
# @return [long]
# @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 lower_bound_percentage_row
super
end
##
# Gets the maximum link over limit count. The count of how many times in a row traffic
# may be over the defined limit for the link before it is shut off entirely. Default
# is 1.
# @rspec_example
# @return [long]
# @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 maximum_link_over_limit_count
super
end
##
# Gets the maximum synchronous monitor request, which is used to control the maximum
# number of monitor requests being sent out at one time for a given probing interval.
# This will allow the user to smooth out monitor probe requests as much as they desire.
# @rspec_example
# @return [long]
# @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 maximum_synchronous_monitor_request
super
end
##
# Gets the over-limit link limit factor. If traffic on a link exceeds the limit, this
# factor will be used instead of the link_limit_factor until the traffic is over limit
# for more than max_link_over_limit_count times. Once the limit has been exceeded too
# many times, all traffic is shut off for the link. The default for over_limit_link_limit_factor
# is 90%.
# @rspec_example
# @return [long]
# @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 over_limit_link_limit_factor
super
end
##
# Gets the number of seconds that a path remains cached after its last access.
# @rspec_example
# @return [long]
# @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 path_duration
super
end
##
# Gets the TTL for the path information.
# @rspec_example
# @return [long]
# @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 path_ttl
super
end
##
# Gets the state indicating whether the dynamic load balancing modes can use path data
# even after the TTL for the path data has expired..
# @rspec_example
# @return [EnabledState]
# @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 paths_never_die_state
super
end
##
# Gets the persistence mask. This function is deprecated and new applications should
# use get_static_persistence_cidr_mask.
# @rspec_example
# @return [long]
# @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 persistence_mask
super
end
##
# Gets the state that if enabled, GTM will still probe disabled object.
# @rspec_example
# @return [EnabledState]
# @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 probe_disabled_object_state
super
end
##
# Gets the factor used to normalize bits per second when the load balancing mode is
# set to LB_METHOD_QOS.
# @rspec_example
# @return [long]
# @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 qos_factor_bps
super
end
##
# Gets the factor used to normalize connection rates when the load balancing mode is
# set to LB_METHOD_QOS. This function is deprecated and new applications should use
# vs_score.
# @rspec_example
# @return [long]
# @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 qos_factor_connection_rate
super
end
##
# Gets the factor used to normalize ping packet completion rates when the load balancing
# mode is set to LB_METHOD_QOS.
# @rspec_example
# @return [long]
# @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 qos_factor_hit_ratio
super
end
##
# Gets the factor used to normalize hops when the load balancing mode is set to LB_METHOD_QOS.
# @rspec_example
# @return [long]
# @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 qos_factor_hops
super
end
##
# Gets the factor used to normalize link capacity valus when the load balancing mode
# is set to LB_METHOD_QOS.
# @rspec_example
# @return [long]
# @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 qos_factor_lcs
super
end
##
# Gets the factor used to normalize packet rates when the load balancing mode is set
# to LB_METHOD_QOS.
# @rspec_example
# @return [long]
# @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 qos_factor_packet_rate
super
end
##
# Gets the factor used to normalize round-trip time valus when the load balancing mode
# is set to LB_METHOD_QOS.
# @rspec_example
# @return [long]
# @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 qos_factor_rtt
super
end
##
# Gets the factor used to normalize topology valus when the load balancing mode is
# set to LB_METHOD_QOS.
# @rspec_example
# @return [long]
# @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 qos_factor_topology
super
end
##
# Gets the factor used to normalize virtual server capacity valus when the load balancing
# mode is set to LB_METHOD_QOS.
# @rspec_example
# @return [long]
# @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 qos_factor_vs_capacity
super
end
##
# Gets the factor used to normalize virtual server (VS) score when the load balancing
# mode is set to LB_METHOD_QOS.
# @rspec_example
# @return [long]
# @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 qos_factor_vs_score
super
end
##
# Gets the state to indicate whether ripeness valu is allowed to be reset.
# @rspec_example
# @return [EnabledState]
# @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 reset_ripeness_state
super
end
##
# Gets the length of the packet sent out in a probe request to determine path information.
# @rspec_example
# @return [long]
# @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 rtt_packet_length
super
end
##
# Gets the number of packets to send out in a probe request to determine path information.
# @rspec_example
# @return [long]
# @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 rtt_sample_count
super
end
##
# Gets the timeout for RTT, in seconds.
# @rspec_example
# @return [long]
# @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 rtt_timeout
super
end
##
# Gets the CIDR mask (length) for the static persistence load balancing mode.
# @rspec_example
# @return [long]
# @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 [boolean] :v6 A boolean indicating which CIDR mask to get, the mask used for protocol IPv4 or IPv6 .
def static_persistence_cidr_mask(opts)
opts = check_params(opts,[:v6])
super(opts)
end
##
# Gets the sync group name.
# @rspec_example
# @return [String]
# @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 sync_group_name
super
end
##
# Gets the state to indicate whether to auto_synchronize named configuration. Allows
# automatic updates of named.conf to/from other 3-DNSes.
# @rspec_example
# @return [EnabledState]
# @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 sync_named_configuration_state
super
end
##
# Gets the sync timeout. If synch'ing from a remote 3-DNS takes longer than this timeout,
# then abort the connection.
# @rspec_example
# @return [long]
# @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 sync_timeout
super
end
##
# Gets the sync zones timeout. If synch'ing named and zone configuration takes this
# timeout, then abort the connection.
# @rspec_example
# @return [long]
# @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 sync_zone_timeout
super
end
##
# Gets the allowable time difference for data to be out of sync between members of
# a sync group.
# @rspec_example
# @return [long]
# @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 time_tolerance
super
end
##
# Gets the frequency at which to retrieve auto-configuration data.
# @rspec_example
# @return [long]
# @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 timer_auto_configuration_data
super
end
##
# Gets the frequency at which to retrieve path and metrics data from the system cache.
# @rspec_example
# @return [long]
# @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 timer_persistence_cache
super
end
##
# Gets the frequency at which to retry path data.
# @rspec_example
# @return [long]
# @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 timer_retry_path_data
super
end
##
# Gets the threshold for the topology ACL.
# @rspec_example
# @return [long]
# @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 topology_acl_threshold
super
end
##
# Gets the state to indicate whether the 3-DNS Controller selects the topology record
# that is most specific and, thus, has the longest match, in cases where there are
# several IP/netmask items that match a particular IP address. If you select No, the
# 3-DNS Controller uses the first topology record that matches (according to the order
# of entry) in the topology statement.
# @rspec_example
# @return [EnabledState]
# @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 topology_longest_match_state
super
end
##
# Gets the port to use to collect traceroute (hops) data.
# @rspec_example
# @return [long]
# @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 traceroute_port
super
end
##
# Gets the TTL for the traceroute information.
# @rspec_example
# @return [long]
# @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 traceroute_ttl
super
end
##
# Gets the state that if enabled, it will set the recursion bit in all DNS responses
# from GTM.
# @rspec_example
# @return [EnabledState]
# @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 use_recursion_bit_state
super
end
##
# Gets the version information for this interface.
# @rspec_example
# @return [String]
def version
super
end
##
# Sets the state to indicate whether local DNS servers that belong to AOL (America
# Online) are recognized.
# @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::EnabledState] :state The state to set.
def set_aol_aware_state(opts)
opts = check_params(opts,[:state])
super(opts)
end
##
# Sets the state indicating whether to auto configure BIGIP/3DNS servers (automatic
# addition and deletion of self IPs and virtual servers.
# @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::EnabledState] :state The state to set.
def set_auto_configure_state(opts)
opts = check_params(opts,[:state])
super(opts)
end
##
# Sets the state to indicate whether to autosync. Allows automatic updates of wideip.conf
# to/from other 3-DNSes.
# @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::EnabledState] :state The state to set.
def set_auto_sync_state(opts)
opts = check_params(opts,[:state])
super(opts)
end
##
# Sets the state to indicate whether to cache LDNSes.
# @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::EnabledState] :state The state to set.
def set_cache_ldns_state(opts)
opts = check_params(opts,[:state])
super(opts)
end
##
# Sets the state to indicate whether to check availability of a path before it uses
# the path for load balancing.
# @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::EnabledState] :state The state to set.
def set_check_dynamic_dependency_state(opts)
opts = check_params(opts,[:state])
super(opts)
end
##
# Sets the state to indicate whether to check the availability of virtual servers.
# @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::EnabledState] :state The state to set.
def set_check_static_dependency_state(opts)
opts = check_params(opts,[:state])
super(opts)
end
##
# Sets the default alternate LB method.
# @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::LBMethod] :lb_method The LB method to set.
def set_default_alternate_lb_method(opts)
opts = check_params(opts,[:lb_method])
super(opts)
end
##
# Sets the default fallback LB method.
# @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::LBMethod] :lb_method The LB method to set.
def set_default_fallback_lb_method(opts)
opts = check_params(opts,[:lb_method])
super(opts)
end
##
# Sets the default probe limit, the number of times to probe a path.
# @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.
def set_default_probe_limit
super
end
##
# Sets the &quot;down_multiple" valu. If a host server or a host virtual server
# has been marked down for the last down_threshold probing cycles (timer_get_host_data
# or timer_get_vs_data respectively), then perform service checks every down_multiple
# * timer period instead.
# @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.
def set_down_multiple
super
end
##
# Sets the &quot;down_threshold" valu. If a host server or a host virtual server
# has been marked down for the last down_threshold probing cycles (timer_get_host_data
# or timer_get_vs_data respectively), then perform service checks every down_multiple
# * timer period instead.
# @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.
def set_down_threshold
super
end
##
# Sets the state to indicate whether persistent connections are allowed to remain connected,
# until TTL expires, when disabling a 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::Common::EnabledState] :state The state to set.
def set_drain_request_state(opts)
opts = check_params(opts,[:state])
super(opts)
end
##
# Sets the state to indicate whether to dump the topology.
# @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::EnabledState] :state The state to set.
def set_dump_topology_state(opts)
opts = check_params(opts,[:state])
super(opts)
end
##
# Sets the state to indicate whether to respect ACL.
# @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::EnabledState] :state The state to set.
def set_fb_respect_acl_state(opts)
opts = check_params(opts,[:state])
super(opts)
end
##
# Sets the state to indicate whether to respect virtual server status when load balancing
# switches to the fallback mode.
# @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::EnabledState] :state The state to set.
def set_fb_respect_dependency_state(opts)
opts = check_params(opts,[:state])
super(opts)
end
##
# Sets the number of seconds that an inactive LDNS remains cached.
# @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.
def set_ldns_duration
super
end
##
# Sets the LDNS probe protocols. The order of the protocols in the sequence will be
# used to indicate the preferred protocols, i.e. the first protocol in the sequence
# is the most preferred protocol. If you'd like to remove an item, get the LDNS probe
# protocols, remove the item, then do set.
# @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::LDNSProbeProtocol] :protocols The probe protocols to set.
def set_ldns_probe_protocols(opts)
opts = check_params(opts,[:protocols])
super(opts)
end
##
# Sets the link compensate inbound state. If set, the link allotment calculation will
# take into account traffic which does not flow through the BIGIP, i.e. if more traffic
# is flowing through a link as measured by SNMP on the router than is flowing through
# the BIGIP. This applies to inbound traffic which the major volume will initiate from
# internal clients.
# @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::EnabledState] :state The state to set.
def set_link_compensate_inbound_state(opts)
opts = check_params(opts,[:state])
super(opts)
end
##
# Sets the link compensate outbound state. If set, the link allotment calculation will
# take into account traffic which does not flow through the BIGIP, i.e. if more traffic
# is flowing through a link as measured by SNMP on the router than is flowing through
# the BIGIP. This applies to outbound traffic which the major volume will initiate
# from internal clients.
# @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::EnabledState] :state The state to set.
def set_link_compensate_outbound_state(opts)
opts = check_params(opts,[:state])
super(opts)
end
##
# Sets the link compensation history.
# @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.
def set_link_compensation_history
super
end
##
# Sets the link limit factor, which is used to set a target percentage for traffic.
# For example, if it is set to 90, the ratio cost based load-balancing will set a ratio
# with a maximum valu equal to 90% of the limit valu for the link. Default is 95%.
# @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.
def set_link_limit_factor
super
end
##
# Sets the link prepaid factor. Maximum percentage of traffic allocated to link which
# has a traffic allotment which has been prepaid. Default is 95%.
# @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.
def set_link_prepaid_factor
super
end
##
# Sets the number of seconds that an inactive LDNS remains cached. This function is
# deprecated (due to being misnamed); new applications should use set_ldns_duration.
# @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.
def set_lnds_duration
super
end
##
# Sets the lower bound percentage column options in Internet Weather Map.
# @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.
def set_lower_bound_percentage_column
super
end
##
# Sets the lower bound percentage row options in Internet Weather Map.
# @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.
def set_lower_bound_percentage_row
super
end
##
# Sets the maximum link over limit count. The count of how many times in a row traffic
# may be over the defined limit for the link before it is shut off entirely. Default
# is 1.
# @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.
def set_maximum_link_over_limit_count
super
end
##
# Sets the maximum synchronous monitor request, which is used to control the maximum
# number of monitor requests being sent out at one time for a given probing interval.
# This will allow the user to smooth out monitor probe requests as much as they desire.
# @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.
def set_maximum_synchronous_monitor_request
super
end
##
# Sets the over-limit link limit factor. If traffic on a link exceeds the limit, this
# factor will be used instead of the link_limit_factor until the traffic is over limit
# for more than max_link_over_limit_count times. Once the limit has been exceeded too
# many times, all traffic is shut off for the link. The default for over_limit_link_limit_factor
# is 90%.
# @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.
def set_over_limit_link_limit_factor
super
end
##
# Sets the number of seconds that a path remains cached after its last access.
# @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.
def set_path_duration
super
end
##
# Sets the TTL for the path information.
# @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.
def set_path_ttl
super
end
##
# Sets the state indicating whether the dynamic load balancing modes can use path data
# even after the TTL for the path data has expired.
# @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::EnabledState] :state The state to set.
def set_paths_never_die_state(opts)
opts = check_params(opts,[:state])
super(opts)
end
##
# Sets the persistence mask. This function is deprecated and new applications should
# use set_static_persistence_cidr_mask.
# @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.
def set_persistence_mask
super
end
##
# Sets the state that if enabled, GTM will still probe disabled object.
# @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::EnabledState] :state The state to set.
def set_probe_disabled_object_state(opts)
opts = check_params(opts,[:state])
super(opts)
end
##
# Sets the factor used to normalize bits per second when the load balancing mode is
# set to LB_METHOD_QOS.
# @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.
def set_qos_factor_bps
super
end
##
# Sets the factor used to normalize connection rates when the load balancing mode is
# set to LB_METHOD_QOS. This function is deprecated and new applications should use
# vs_score.
# @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.
def set_qos_factor_connection_rate
super
end
##
# Sets the factor used to normalize ping packet completion rates when the load balancing
# mode is set to LB_METHOD_QOS.
# @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.
def set_qos_factor_hit_ratio
super
end
##
# Sets the factor used to normalize hops when the load balancing mode is set to LB_METHOD_QOS.
# @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.
def set_qos_factor_hops
super
end
##
# Sets the factor used to normalize link capacity valus when the load balancing mode
# is set to LB_METHOD_QOS.
# @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.
def set_qos_factor_lcs
super
end
##
# Sets the factor used to normalize packet rates when the load balancing mode is set
# to LB_METHOD_QOS.
# @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.
def set_qos_factor_packet_rate
super
end
##
# Sets the factor used to normalize round-trip time valus when the load balancing mode
# is set to LB_METHOD_QOS.
# @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.
def set_qos_factor_rtt
super
end
##
# Sets the factor used to normalize topology valus when the load balancing mode is
# set to LB_METHOD_QOS.
# @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.
def set_qos_factor_topology
super
end
##
# Sets the factor used to normalize virtual server capacity valus when the load balancing
# mode is set to LB_METHOD_QOS.
# @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.
def set_qos_factor_vs_capacity
super
end
##
# Sets the factor used to normalize virtual server (VS) score when the load balancing
# mode is set to LB_METHOD_QOS.
# @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.
def set_qos_factor_vs_score
super
end
##
# Sets the state to indicate whether ripeness valu is allowed to be reset.
# @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::EnabledState] :state The state to set.
def set_reset_ripeness_state(opts)
opts = check_params(opts,[:state])
super(opts)
end
##
# Sets the length of the packet sent out in a probe request to determine path information.
# @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.
def set_rtt_packet_length
super
end
##
# Sets the number of packets to send out in a probe request to determine path information.
# @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.
def set_rtt_sample_count
super
end
##
# Sets the timeout for RTT, in seconds.
# @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.
def set_rtt_timeout
super
end
##
# Sets the CIDR mask (length) for the static persistence load balancing mode.
# @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 [boolean] :v6 A boolean indicating which CIDR mask to affect, the mask used for protocol IPv4 or IPv6 .
def set_static_persistence_cidr_mask(opts)
opts = check_params(opts,[:v6])
super(opts)
end
##
# Sets the sync group name.
# @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 [String] :sync_group_name The sync group name to set.
def set_sync_group_name(opts)
opts = check_params(opts,[:sync_group_name])
super(opts)
end
##
# Sets the state to indicate whether to auto-synchronize named configuration. Allows
# automatic updates of named.conf to/from other 3-DNSes.
# @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::EnabledState] :state The state to set.
def set_sync_named_configuration_state(opts)
opts = check_params(opts,[:state])
super(opts)
end
##
# Sets the sync timeout. If synch'ing from a remote 3-DNS takes longer than this timeout,
# then abort the connection.
# @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.
def set_sync_timeout
super
end
##
# Sets the sync zones timeout. If synch'ing named and zone configuration takes this
# timeout, then abort the connection.
# @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.
def set_sync_zone_timeout
super
end
##
# Sets the allowable time difference for data to be out of sync between members of
# a sync group.
# @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.
def set_time_tolerance
super
end
##
# Sets the frequency at which to retrieve auto-configuration data.
# @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.
def set_timer_auto_configuration_data
super
end
##
# Sets the frequency at which to retrieve path and metrics data from the system cache.
# @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.
def set_timer_persistence_cache
super
end
##
# Sets the frequency at which to retry path data.
# @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.
def set_timer_retry_path_data
super
end
##
# Sets the threshold for the topology ACL.
# @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.
def set_topology_acl_threshold
super
end
##
# Sets the state to indicate whether the 3-DNS Controller selects the topology record
# that is most specific and, thus, has the longest match, in cases where there are
# several IP/netmask items that match a particular IP address. If you select No, the
# 3-DNS Controller uses the first topology record that matches (according to the order
# of entry) in the topology statement.
# @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::EnabledState] :state The state to set.
def set_topology_longest_match_state(opts)
opts = check_params(opts,[:state])
super(opts)
end
##
# Sets the port to use to collect traceroute (hops) data.
# @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.
def set_traceroute_port
super
end
##
# Sets the TTL for the traceroute information.
# @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.
def set_traceroute_ttl
super
end
##
# Sets the state that if enabled, it will set the recursion bit in all DNS responses
# from GTM.
# @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::EnabledState] :state The state to set.
def set_use_recursion_bit_state(opts)
opts = check_params(opts,[:state])
super(opts)
end
end
end
|
#!/usr/bin/env ruby
require 'TestSetup'
require 'test/unit'
#require 'rubygems'
require 'ibruby'
include IBRuby
class RowTest < Test::Unit::TestCase
CURDIR = "#{Dir.getwd}"
DB_FILE = "#{CURDIR}#{File::SEPARATOR}row_unit_test.ib"
def setup
puts "#{self.class.name} started." if TEST_LOGGING
if File::exist?(DB_FILE)
Database.new(DB_FILE).drop(DB_USER_NAME, DB_PASSWORD)
end
database = Database::create(DB_FILE, DB_USER_NAME, DB_PASSWORD)
@connection = database.connect(DB_USER_NAME, DB_PASSWORD)
@transaction = @connection.start_transaction
@results = ResultSet.new(@connection, @transaction,
'SELECT * FROM RDB$FIELDS', 3, nil)
@empty = [[0, SQLType::INTEGER], [0, SQLType::INTEGER],
[0, SQLType::INTEGER], [0, SQLType::INTEGER],
[0, SQLType::INTEGER], [0, SQLType::INTEGER],
[0, SQLType::INTEGER], [0, SQLType::INTEGER],
[0, SQLType::INTEGER], [0, SQLType::INTEGER],
[0, SQLType::INTEGER], [0, SQLType::INTEGER],
[0, SQLType::INTEGER], [0, SQLType::INTEGER],
[0, SQLType::INTEGER], [0, SQLType::INTEGER],
[0, SQLType::INTEGER], [0, SQLType::INTEGER],
[0, SQLType::INTEGER], [0, SQLType::INTEGER],
[0, SQLType::INTEGER], [0, SQLType::INTEGER],
[0, SQLType::INTEGER], [0, SQLType::INTEGER],
[0, SQLType::INTEGER], [0, SQLType::INTEGER],
[0, SQLType::INTEGER], [0, SQLType::INTEGER]]
@connection.start_transaction do |tx|
tx.execute('create table rowtest (COL01 integer, COL02 varchar(10), '\
'COL03 integer)')
tx.execute('create table all_types (col01 boolean, col02 blob, '\
'col03 char(100), col04 date, col05 decimal(5,2), '\
'col06 double precision, col07 float, col08 integer, '\
'col09 numeric(10,3), col10 smallint, col11 time, '\
'col12 timestamp, col13 varchar(23))')
end
@connection.start_transaction do |tx|
tx.execute("insert into rowtest values (1, 'Two', 3)")
stmt = Statement.new(@connection, tx,
"insert into all_types values(?, ?, ?, ?, ?, ?, "\
"?, ?, ?, ?, ?, ?, ?)",
3)
#stmt.execute_for([nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil])
stmt.execute_for([false, nil, 'La la la', Date.new(2005, 10, 29),
10.23, 100.751, 56.25, 12345, 19863.21, 123,
Time.new, Time.new, 'The End!'])
end
end
def teardown
@results.close
@transaction.rollback
@connection.close
if File::exist?(DB_FILE)
Database.new(DB_FILE).drop(DB_USER_NAME, DB_PASSWORD)
end
puts "#{self.class.name} finished." if TEST_LOGGING
end
def test01
row = Row.new(@results, @empty, 100)
assert(row.column_count == 28)
assert(row.number == 100)
assert(row.column_name(0) == 'RDB$FIELD_NAME')
assert(row.column_alias(10) == 'RDB$FIELD_TYPE')
assert(row[0] == 0)
assert(row['RDB$FIELD_TYPE'] == 0)
end
def test02
sql = 'select COL01 one, COL02 two, COL03 three from rowtest'
rows = @connection.execute_immediate(sql)
data = rows.fetch
count = 0
data.each do |name, value|
assert(['ONE', 'TWO', 'THREE'].include?(name))
assert([1, 'Two', 3].include?(value))
count += 1
end
assert(count == 3)
count = 0
data.each_key do |name|
assert(['ONE', 'TWO', 'THREE'].include?(name))
count += 1
end
assert(count == 3)
count = 0
data.each_value do |value|
assert([1, 'Two', 3].include?(value))
count += 1
end
assert(count == 3)
assert(data.fetch('TWO') == 'Two')
assert(data.fetch('FOUR', 'LALALA') == 'LALALA')
assert(data.fetch('ZERO') {'NOT FOUND'} == 'NOT FOUND')
begin
data.fetch('FIVE')
assert(false, 'Row#fetch succeeded for non-existent column name.')
rescue IndexError
end
assert(data.has_key?('ONE'))
assert(data.has_key?('TEN') == false)
assert(data.has_column?('COL02'))
assert(data.has_column?('COL22') == false)
assert(data.has_alias?('TWO'))
assert(data.has_alias?('FOUR') == false)
assert(data.has_value?(3))
assert(data.has_value?('LALALA') == false)
assert(data.keys.size == 3)
data.keys.each do |name|
assert(['ONE', 'TWO', 'THREE'].include?(name))
end
assert(data.names.size == 3)
data.names.each do |name|
assert(['COL01', 'COL02', 'COL03'].include?(name))
end
assert(data.aliases.size == 3)
data.aliases.each do |name|
assert(['ONE', 'TWO', 'THREE'].include?(name))
end
assert(data.values.size == 3)
data.values.each do |value|
assert([1, 'Two', 3].include?(value))
end
array = data.select {|name, value| name == 'TWO'}
assert(array.size == 1)
assert(array[0][0] == 'TWO')
assert(array[0][1] == 'Two')
array = data.to_a
assert(array.size == 3)
assert(array.include?(['ONE', 1]))
assert(array.include?(['TWO', 'Two']))
assert(array.include?(['THREE', 3]))
hash = data.to_hash
assert(hash.length == 3)
assert(hash['ONE'] == 1)
assert(hash['TWO'] == 'Two')
assert(hash['THREE'] == 3)
array = data.values_at('TEN', 'TWO', 'THREE')
assert(array.size == 3)
assert(array.include?('Two'))
assert(array.include?(3))
assert(array.include?(nil))
rows.close
end
def test03
results = nil
row = nil
begin
results = @connection.execute_immediate('select * from all_types')
row = results.fetch
assert(row.get_base_type(0) == SQLType::BOOLEAN)
assert(row.get_base_type(1) == SQLType::BLOB)
assert(row.get_base_type(2) == SQLType::CHAR)
assert(row.get_base_type(3) == SQLType::DATE)
assert(row.get_base_type(4) == SQLType::DECIMAL)
assert(row.get_base_type(5) == SQLType::DOUBLE)
assert(row.get_base_type(6) == SQLType::FLOAT)
assert(row.get_base_type(7) == SQLType::INTEGER)
assert(row.get_base_type(8) == SQLType::NUMERIC)
assert(row.get_base_type(9) == SQLType::SMALLINT)
assert(row.get_base_type(10) == SQLType::TIME)
assert(row.get_base_type(11) == SQLType::TIMESTAMP)
assert(row.get_base_type(12) == SQLType::VARCHAR)
ensure
results.close if results != nil
end
end
end
|
# frozen_string_literal: true
RSpec.describe Kiosk, type: :model do
let(:test_layout) { KioskLayout.create!(name: 'touch') }
it 'is valid with valid attributes' do
expect(Kiosk.new(name: 'test', kiosk_layout_id: test_layout.id)).to be_valid
end
it 'is not valid without a title' do
kiosk = Kiosk.new(name: nil, kiosk_layout_id: nil)
expect(kiosk).not_to be_valid
end
it 'is not valid with a restart_at datetime in the past' do
kiosk = Kiosk.new(name: 'test', kiosk_layout_id: test_layout.id, restart_at: Date.yesterday)
expect(kiosk).not_to be_valid
end
context 'when #should_restart?' do
let(:restart_at) { Time.zone.parse('2018-01-17 07:30:00') }
let(:kiosk) { Kiosk.new(name: 'test', kiosk_layout_id: test_layout.id, restart_at: restart_at, restart_at_active: true) }
it 'restarts now' do
now = Time.zone.parse('2018-01-17 07:30:10')
allow(Time).to receive(:now) { now }
expect(kiosk).to be_should_restart
end
it 'does not restart now' do
now = Time.zone.parse('2018-01-17 07:29:10')
allow(Time).to receive(:now) { now }
expect(kiosk).not_to be_should_restart
end
end
context 'when #restart_pending?' do
let(:restart_at) { Time.zone.parse('2018-01-17 07:30:00') }
let(:kiosk) { Kiosk.new(name: 'test', kiosk_layout_id: test_layout.id, restart_at: restart_at, restart_at_active: true) }
it 'restart is pending' do
now = Time.zone.parse('2018-01-17 06:30:10')
allow(Time).to receive(:now) { now }
expect(kiosk).to be_restart_pending
end
it 'kiosk is restarted' do
now = Time.zone.parse('2018-01-17 08:30:00')
allow(Time).to receive(:now) { now }
expect(kiosk).not_to be_restart_pending
end
end
end
|
class FixNonNullBody < ActiveRecord::Migration
def self.up
execute "ALTER TABLE `work_logs` CHANGE `body` `body` TEXT DEFAULT NULL"
end
def self.down
execute "ALTER TABLE `work_logs` CHANGE `body` `body` TEXT NOT NULL"
end
end
|
# frozen_string_literal: true
require 'httparty'
require 'openssl'
require 'nokogiri'
require 'open-uri'
require 'pry'
class Scraper
class << self
BASE_URL = 'http://localhost:3000/'
def crawl(search_term)
payload = query('admin/verify')
document = Nokogiri::HTML(payload)
qr_code = query('admin/mfa_qr')
# result_set = document.css('.listingResult')
# headlines = result_set.css('.article-link>.search-result>.content>header>h3')
# text = headlines.map(&:text)
end
private
def query(resource)
HTTParty.get(BASE_URL + resource, basic_auth: { username: 'raging', password: 'tortoise' })
end
end
end
Scraper.crawl('amd threadripper')
|
require_relative 'guess'
class GuessBuilder
def build(input, sequence_length)
code = input.downcase.chars
guess = Guess.new(code, sequence_length)
if guess.valid?
guess
else
false
end
end
end
if __FILE__ == $0
gb = GuessBuilder.new.build("rrrr")
end
|
class RestaurantDish < ApplicationRecord
belongs_to :dishe
belongs_to :restaurant
end
|
FactoryBot.define do
factory :payment do
token { '123' }
postal_code { '100-0000' }
prefecture_id { '2' }
city { '長野市' }
addresses { '吉田' }
phone_number { '00000000000' }
association :user
association :item
end
end
|
# frozen_string_literal: true
ENV["RAILS_ENV"] ||= "test"
require "combustion"
require "timecop"
require "pry-byebug"
require "simplecov"
require "rake"
if ENV["CODE_COVERAGE"] == "true"
SimpleCov.command_name Rails.gem_version.to_s
SimpleCov.start do
add_filter "spec"
end
end
# make sure injected modules are required
require "pg_party/model/shared_methods"
require "pg_party/model/range_methods"
require "pg_party/model/list_methods"
require "pg_party/model/hash_methods"
Combustion.path = "spec/dummy"
Combustion.initialize! :active_record do
config.eager_load = true
end
load "support/db.rake"
require "rspec/rails"
require "rspec/its"
require "database_cleaner"
require "support/uuid_matcher"
require "support/heredoc_matcher"
require "support/pg_dump_helper"
require "support/pg_version_helper"
static_time = Date.current + 12.hours
RSpec.configure do |config|
# Enable flags like --only-failures and --next-failure
config.example_status_persistence_file_path = ".rspec_status"
# Disable RSpec exposing methods globally on `Module` and `main`
config.disable_monkey_patching!
config.mock_with :rspec do |c|
c.verify_partial_doubles = true
end
config.expect_with :rspec do |c|
c.syntax = :expect
end
config.use_transactional_fixtures = false
config.before(:suite) do
DatabaseCleaner.strategy = :truncation
end
config.around(:each) do |example|
Timecop.freeze(static_time)
PgParty.reset
DatabaseCleaner.start
example.run
DatabaseCleaner.clean
end
end
|
# frozen_string_literal: true
require 'rails_helper'
RSpec.describe 'Lesson API', type: :request do
include_context 'super_admin_request'
let(:lesson) { json['lesson'] }
let(:lessons) { json['lessons'] }
let(:group) { json['lesson']['group'] }
let(:subject) { json['lesson']['subject'] }
describe 'GET /lessons/:id' do
before :each do
@group = create :group
@subject = create :subject
@lesson = create :lesson, group: @group, subject: @subject
end
it 'responds with a specific lesson' do
get_with_token lesson_path(@lesson), as: :json
expect(lesson['id']).to eq @lesson.id
expect(lesson['group_id']).to eq @lesson.group_id
expect(lesson['subject_id']).to eq @lesson.subject_id
expect(lesson['date']).to eq @lesson.date.to_s
end
it 'responds with timestamp' do
get_with_token lesson_path(@lesson), as: :json
expect(response_timestamp).to be_within(1.second).of Time.zone.now
end
it 'responds with a specific lesson including group' do
get_with_token lesson_path(@lesson), params: { include: 'group' }, as: :json
expect(group['id']).to eq @group.id
expect(group['group_name']).to eq @group.group_name
end
it 'responds with a specific lesson including subject' do
get_with_token lesson_path(@lesson), params: { include: 'subject' }, as: :json
expect(subject['id']).to eq @subject.id
expect(subject['subject_name']).to eq @subject.subject_name
end
describe 'v2' do
it 'responds with a specific lesson by UUID' do
get_v2_with_token lesson_path(id: @lesson.reload.uid), as: :json
expect(lesson['id']).to eq @lesson.uid
expect(lesson['group_id']).to eq @lesson.group_id
expect(lesson['subject_id']).to eq @lesson.subject_id
expect(lesson['date']).to eq @lesson.date.to_s
end
end
end
describe 'GET /lessons' do
before :each do
@group1 = create :group
@group2 = create :group
@subject1 = create :subject
@subject2 = create :subject
@lesson1, @lesson2 = create_list :lesson, 2, subject: @subject1, group: @group1, deleted_at: Time.zone.now
@lesson3 = create :lesson, subject: @subject2, group: @group2
end
it 'responds with a list of lessons' do
get_with_token lessons_path, as: :json
expect(lessons.length).to eq 3
expect(lessons.map { |l| l['id'] }).to include @lesson1.id, @lesson2.id, @lesson3.id
end
it 'responds with timestamp' do
get_with_token lessons_path, as: :json
expect(response_timestamp).to be_within(1.second).of Time.zone.now
end
it 'responds only with lessons created or updated after a certain time' do
create :lesson, created_at: 3.months.ago, updated_at: 3.months.ago
create :lesson, created_at: 2.months.ago, updated_at: 2.months.ago
create :lesson, created_at: 4.months.ago, updated_at: 1.hour.ago
get_with_token lessons_path, params: { after_timestamp: 1.day.ago }, as: :json
expect(lessons.length).to eq 4
end
it 'responds only with lessons belonging to a specific group' do
get_with_token lessons_path, params: { group_id: @group1.id }, as: :json
expect(lessons.length).to eq 2
expect(lessons.map { |s| s['id'] }).to include @lesson1.id, @lesson2.id
end
it 'responds only with lessons in a specific subject' do
get_with_token lessons_path, params: { subject_id: @subject1.id }, as: :json
expect(lessons.length).to eq 2
expect(lessons.map { |s| s['id'] }).to include @lesson1.id, @lesson2.id
end
describe 'v2' do
it 'responds with a list of lessons with UUIDs for IDs' do
get_v2_with_token lessons_path, as: :json
expect(response).to be_successful
expect(lessons.length).to eq 3
expect(lessons.map { |l| l['id'] }).to include @lesson1.reload.uid, @lesson2.reload.uid, @lesson3.reload.uid
end
end
end
describe 'POST /lessons' do
before :each do
@subject = create :subject
@group = create :group
end
context 'creating a new lesson' do
before :each do
post_with_token lessons_path, as: :json, params: { group_id: @group.id, subject_id: @subject.id, date: Time.zone.today.to_formatted_s }
end
it 'creates a new lesson' do
lesson = Lesson.last
expect(lesson.subject_id).to eq @subject.id
expect(lesson.group_id).to eq @group.id
expect(lesson.date).to eq Time.zone.today
end
it 'has a Location header with the resource URL' do
expect(response.headers['Location']).to eq api_lesson_url id: Lesson.last.id
end
end
context 'lesson already exists' do
before :each do
create :lesson, group_id: @group.id, subject_id: @subject.id, date: Time.zone.today.to_formatted_s
post_with_token lessons_path, as: :json, params: { group_id: @group.id, subject_id: @subject.id, date: Time.zone.today.to_formatted_s }
end
it 'responds with lesson' do
expect(lesson['subject_id']).to eq @subject.id
expect(lesson['group_id']).to eq @group.id
expect(Time.zone.parse(lesson['date'])).to eq Time.zone.today
end
it 'does not save the new lesson' do
expect(Lesson.all.length).to eq 1
end
end
describe 'v2' do
context 'creating a new lesson' do
it 'creates a new lesson with the passed UUID' do
post_v2_with_token lessons_path, as: :json, params: { id: '5e9d2b0e-1dc6-4c04-b70c-9d67c20b083e', group_id: @group.id, subject_id: @subject.id, date: Time.zone.today.to_formatted_s }
new_lesson = Lesson.last
expect(new_lesson.uid).to eq '5e9d2b0e-1dc6-4c04-b70c-9d67c20b083e'
expect(new_lesson.subject_id).to eq @subject.id
expect(new_lesson.group_id).to eq @group.id
expect(new_lesson.date).to eq Time.zone.today
expect(lesson['id']).to eq '5e9d2b0e-1dc6-4c04-b70c-9d67c20b083e'
end
it 'creates a new lesson without the passed UUID' do
post_v2_with_token lessons_path, as: :json, params: { group_id: @group.id, subject_id: @subject.id, date: Time.zone.today.to_formatted_s }
new_lesson = Lesson.last
expect(new_lesson.subject_id).to eq @subject.id
expect(new_lesson.group_id).to eq @group.id
expect(new_lesson.date).to eq Time.zone.today
expect(lesson['id']).to eq new_lesson.uid
end
it 'has a Location header with the resource URL' do
post_v2_with_token lessons_path, as: :json, params: { id: '5e9d2b0e-1dc6-4c04-b70c-9d67c20b083e', group_id: @group.id, subject_id: @subject.id, date: Time.zone.today.to_formatted_s }
expect(response.headers['Location']).to eq api_lesson_url id: '5e9d2b0e-1dc6-4c04-b70c-9d67c20b083e'
end
end
context 'lesson already exists' do
before :each do
@existing_lesson = create :lesson, uid: '5e9d2b0e-1dc6-4c04-b70c-9d67c20b083e', group_id: @group.id, subject_id: @subject.id, date: Time.zone.today.to_formatted_s
post_v2_with_token lessons_path, as: :json, params: { group_id: @group.id, subject_id: @subject.id, date: Time.zone.today.to_formatted_s }
end
it 'responds with existing lesson' do
expect(lesson['id']).to eq '5e9d2b0e-1dc6-4c04-b70c-9d67c20b083e'
expect(lesson['subject_id']).to eq @subject.id
expect(lesson['group_id']).to eq @group.id
expect(Time.zone.parse(lesson['date'])).to eq Time.zone.today
end
end
end
end
end
|
module Pelita
module Util
module Db
def fetch_db_config(file)
db_config = File.read(file)
db_config = ERB.new(db_config).result
db_config = YAML.safe_load(db_config)
db_config
end
module_function :fetch_db_config
public :fetch_db_config
def generate_connection_string(db_config)
conn_string = db_config['adapter']
unless db_config['host'].blank?
host_string = db_config['host']
host_string = "#{host_string}:#{db_config["port"]}" unless db_config['port'].blank?
unless db_config['username'].blank?
user_string = db_config['username']
user_string = "#{user_string}:#{db_config["password"]}" unless db_config['password'].blank?
host_string = "#{user_string}@#{host_string}"
end
conn_string = "#{conn_string}://#{host_string}"
conn_string = "#{conn_string}/#{db_config["database"]}" unless db_config['database'].blank?
end
conn_string
end
module_function :generate_connection_string
public :generate_connection_string
end
end
end
|
require 'gfa/record/has_from_to'
class GFA::Record::Link < GFA::Record
CODE = :L
REQ_FIELDS = %i[from from_orient to to_orient overlap]
OPT_FIELDS = {
MQ: :i, # Mapping quality
NM: :i, # Number of mismatches/gaps
EC: :i, # Read count
FC: :i, # Fragment count
KC: :i, # k-mer count
ID: :Z # Edge identifier
}
REQ_FIELDS.each_index do |i|
define_method(REQ_FIELDS[i]) { fields[i + 2] }
end
OPT_FIELDS.each_key { |i| define_method(i) { fields[i] } }
include GFA::Record::HasFromTo
def initialize(from, from_orient, to, to_orient, overlap, *opt_fields)
@fields = {}
add_field(2, :Z, from, /[!-)+-<>-~][!-~]*/)
add_field(3, :Z, from_orient, /[+-]/)
add_field(4, :Z, to, /[!-)+-<>-~][!-~]*/)
add_field(5, :Z, to_orient, /[+-]/)
add_field(6, :Z, overlap, /\*|([0-9]+[MIDNSHPX=])+/)
opt_fields.each { |f| add_opt_field(f, OPT_FIELDS) }
end
end
|
class LecturesController < ApplicationController
before_filter :authenticate_user!
before_filter :check_admin_status
before_action :set_lecture, only: [:show, :edit, :update, :destroy]
def index
@lectures = Lecture.all
end
def show
end
def new
@lecture = Lecture.new
@host_user_id = current_user.id
end
def edit
end
def create
@lecture = Lecture.create(lecture_params)
redirect_to lectures_url
end
def update
@lecture.update(lecture_params)
redirect_to lectures_url
end
def destroy
@lecture.destroy
redirect_to lectures_url
end
private
def set_lecture
@lecture = Lecture.find(params[:id])
end
def lecture_params
params.require(:lecture).permit(:id, :name, :description, :url, :host_user_id, :lecture_date, :lecture_time)
end
end
|
class SpreeCmcicController < ApplicationController
respond_to :html
def show
@order = Spree::Order.find(params[:order_id])
@gateway = @order.available_payment_methods.find{|x| x.id == params[:gateway_id].to_i }
if @order.blank? || @gateway.blank?
flash[:error] = I18n.t('invalid_arguments')
redirect_to :back
else
@order.update_attribute(:payment_date, @order.updated_at)
end
respond_to do |format|
format.html { render 'show', :layout => false }
end
end
end
|
FactoryGirl.define do
factory :state do
code { Faker::Address.state_abbr }
name { Faker::Address.state }
country nil
end
end |
#encoding: utf-8
class Boat < ActiveRecord::Base
serialize :options, ActiveRecord::Coders::Hstore
attr_accessible :boat_category_id, :model, :options, :price, :url_title, :images_attributes, :motor, :title
belongs_to :boat_category
acts_as_list scope: :boat_category
has_many :images, :as => :imageable
has_many :cart_items, :as => :cartable
accepts_nested_attributes_for :images, :allow_destroy => true
default_scope includes(:boat_category).includes(:images)
scope :motor, where(:motor => true)
scope :non_motor, where(:motor => false)
scope :active, where(:active => true)
scope :has_carrying, where("CAST (options -> 'carrying' AS FLOAT) IS NOT NULL")
scope :categories, lambda {|categories| where(:boat_category_id => categories)}
scope :motor_type, lambda {|motor| where(:motor => motor)}
scope :price_range, lambda {|price_range| where("CAST (price AS FLOAT) >= #{price_range["minval"]} AND CAST (price AS FLOAT) <= #{price_range["maxval"]}")}
scope :length_range, lambda {|length_range| where("CAST (options -> 'length' AS INTEGER) >= #{length_range["minval"]} AND CAST (options -> 'length' AS INTEGER) <= #{length_range["maxval"]}")}
scope :motor_power_range, lambda {|motor_power_range| where("CAST (options -> 'motor_power' AS FLOAT) >= #{motor_power_range["minval"]} AND CAST (options -> 'motor_power' AS FLOAT) <= #{motor_power_range["maxval"]}")}
scope :carrying_range, lambda {|carrying_range| where("CAST (options -> 'carrying' AS FLOAT) >= #{carrying_range["minval"]} AND CAST (options -> 'carrying' AS FLOAT) <= #{carrying_range["maxval"]}")}
before_save :build_title
self.per_page = 16
include PgSearch
multisearchable :against => :title
def update_with_options(params)
params[:options].each do |key, value|
self.options = (options || {}).merge(key => value)
end
params.delete(:options)
update_attributes(params)
end
def options_val(key)
options && options[key]
end
def cart_item_title
"Лодка #{boat_category.title} #{model}"
end
def price_for_cart
price
end
def buy_price
"Н/д"
end
def build_title
title = "Лодка #{boat_category.title} #{model}"
end
end
|
class ActiveChat < ActiveRecord::Base
belongs_to :user
belongs_to :admin
validates :user_id, uniqueness: {scope: :admin_id}, presence: true
validates :admin_id, uniqueness: {scope: :user_id}, presence: true
default_scope {includes(:user, :admin)}
delegate :name, to: :user, prefix: true
delegate :name, to: :admin, prefix: true
def name
"#{user_name} & #{admin_name}" rescue '--'
end
def message_channel
@message_channel ||= "/chats/#{id}"
end
def messages
@messages ||= Message.where(user: user, admin: admin)
end
end
|
When(/I wait (.*) seconds?/) do |seconds|
sleep(seconds.to_i)
end
|
CryptDemo::Application.routes.draw do
root "demo#index"
resources :demo
end
|
require "spec_helper"
describe "Login" do
it "renders baby" do
visit "/login"
page.should have_content "Login"
end
describe "requesting a login link" do
context "with invalid email" do
it "display invalid email message" do
login("test")
expect(page).to have_content "That doesn't look like a valid email address."
end
end
context "with valid email" do
it "redirects to / with notice and sends email" do
login("test@aol.com")
expect(current_url).to eq root_url
expect(page).to have_content "Your log in link has been emailed to you."
expect(last_email.to).to include "test@aol.com"
end
end
end
describe "validating a login link" do
context "when non-existent" do
it "gives notice that the login link is invalid and redirects" do
visit "/login/1/asdf"
expect(page).to have_content "This is not a valid login link."
expect(current_url).to eq root_url
end
end
context "when already used" do
it "gives notice that the login link is already used and redirects" do
ls = FactoryGirl.create(:login_session)
code = ls.code
ls.update_attributes(activated_at: Time.now)
visit "/login/#{ls.id}/#{code}"
expect(page).to have_content "This login link has already been used."
expect(current_url).to eq root_url
end
end
context "when older than 60 min" do
it "gives notice that the login link is expired and redirects" do
ls = FactoryGirl.create(:login_session, created_at: 65.minutes.ago)
visit "/login/#{ls.id}/#{ls.code}"
expect(page).to have_content "This login link has expired."
expect(current_url).to eq root_url
end
end
context "when valid" do
context "when user doens't already exist" do
it "sets session, creates user, and redirects" do
ls = FactoryGirl.create(:login_session)
expect {
visit "/login/#{ls.id}/#{ls.code}"
}.to change{ User.count }.by(1)
expect(page).to have_content "Welcome back!"
expect(current_url).to eq home_url
end
end
context "when user already exists" do
it "sets session, finds user, and redirects" do
ls = FactoryGirl.create(:login_session)
user = FactoryGirl.create(:user)
expect {
visit "/login/#{ls.id}/#{ls.code}"
}.to change{ User.count }.by(0)
expect(page).to have_content "Welcome back!"
expect(current_url).to eq home_url
end
end
end
end
describe "requiring authentication" do
context "when accessing a secure page" do
it "redirects to login page with notice" do
visit "/home"
expect(page).to have_content "Please login."
expect(current_url).to eq login_sessions_url
end
end
end
describe "logging out" do
context "when logging out" do
it "doesn't allow access to a secure page" do
ls = FactoryGirl.create(:login_session)
user = FactoryGirl.create(:user)
expect {
visit "/login/#{ls.id}/#{ls.code}"
}.to change{ User.count }.by(0)
visit "/logout"
visit "/home"
expect(page).to have_content "Please login."
expect(current_url).to eq login_sessions_url
end
end
end
end
|
require "chef/knife"
class Chef
class Knife
module GlesysBase
def self.included(includer)
includer.class_eval do
deps do
require 'fog'
require 'readline'
require 'chef/json_compat'
end
option :glesys_api_key,
:short => "-A KEY",
:long => "--glesys-api-key KEY",
:description => "Your Glesys API key",
:proc => Proc.new { |key| Chef::Config[:knife][:glesys_api_key] = key }
option :glesys_username,
:short => "-U USERNAME",
:long => "--glesys-username USERNAME",
:description => "Your Glesysusername",
:proc => Proc.new { |key| Chef::Config[:knife][:glesys_username] = key }
end
end
def connection
@connection ||= begin
connection = Fog::Compute.new(
:provider => 'Glesys',
:glesys_api_key => Chef::Config[:knife][:glesys_api_key],
:glesys_username => Chef::Config[:knife][:glesys_username],
)
end
end
def msg_pair(label, value, color=:cyan)
if value && !value.to_s.empty?
puts "#{ui.color(label, color)}: #{value}"
end
end
def locate_config_value(key)
key = key.to_sym
config[key] || Chef::Config[:knife][key]
end
def color_state(state)
return ui.color("unknown", :cyan) if state.nil?
case state.to_s.downcase
when 'shutting-down','terminated','stopping','stopped' then ui.color(state, :red)
when 'pending', 'locked' then ui.color(state, :yellow)
else ui.color(state, :green)
end
end
def validate!
end
end
end
end
|
class Book < ApplicationRecord
validates_presence_of :title
validates_presence_of :pages
validates_presence_of :year
has_many :book_authors
has_many :authors, through: :book_authors
has_many :reviews
def average_rating
reviews.average(:rating).to_f
end
def self.sorted_by_reviews(direction)
select("books.*, avg(rating) AS avg_rating")
.joins(:reviews)
.group(:book_id, :id)
.order("avg_rating #{direction}")
end
def self.sorted_by_pages(direction)
order("pages #{direction}")
end
def self.sorted_by_reviews_count(direction)
books = select("books.*, count(reviews.id) AS total_reviews")
.joins(:reviews)
.group(:book_id, :id)
.order("total_reviews #{direction}")
end
def self.sorted_by_reviews_limited_to(count, direction)
sorted_by_reviews(direction).limit(count)
end
def self.create_book(params)
if Book.find_by(title: params[:title]) == nil && Author.find_by(name: params[:authors]) == nil
author = Author.create(name: params[:authors])
book = author.books.create(title: params[:title], pages: params[:pages], year: params[:year])
elsif Book.find_by(title: params[:title]) && Author.find_by(name: params[:authors]) == nil
author = Author.create(name: params[:authors])
book = Book.find_by(title: params[:title])
author.books << book
elsif Book.find_by(title: params[:title]) == nil && Author.find_by(name: params[:authors])
author = Author.find_by(name: params[:authors])
book = author.books.create(title: params[:title], pages: params[:pages], year: params[:year])
else
book = Book.find_by(title: params[:title])
Author.find_by(name: params[:authors]).books << book
end
book
end
def most_extreme_reviews(limited_to, direction)
direction = direction.to_sym
reviews.order(rating: direction).limit(limited_to)
end
def best_review
most_extreme_reviews(1, 'DESC').first
end
end
|
require 'spec_helper'
# require './db/seeds.rb'
describe 'employees controller' do
it 'should return all employees' do
employees = Employee.all
names = []
employees.each{|e| names << e.first_name}
get '/employees'
expect(last_response.status).to eq 200
expect(employees.count).to eq 8
names.each do |name|
expect(last_response.body).to include(name)
end
end
end
|
require "erubis"
require "commuter/file_model"
require "rack/request"
module Commuter
class Controller
# To pass this to the app controllers folder so we can use filemodl instead of Commuter::Model::FileModel
include Commuter::Model
def initialize(env)
@env = env
end
def env
@env
end
def request
@request ||= Rack::Request.new(@env)
end
def params
request.params
end
def response(text, status = 200, headers = {})
raise "Aye, hello there" if @response
a = [text].flatten
@response = Rack::response.new(a, status, headers)
end
def get_response
@response
end
def render_response(*args)
response(render(*args))
end
def render(view_name, locals ={})
filename = File.join "app","views", "#{view_name}.html.erb"
template = File.read filename
eruby = Erubis::Eruby.new(template)
eruby.result locals.merge(:env => env)
end
def controller_name
klass = self.class
klass = klass.to_s.gsub /Controller$/, ""
Commuter.to_underscore klass
end
end
end
|
class Teacher < ActiveRecord::Base
has_many :grade_levels
has_many :students, through: :grade_levels
def tenure
years_of_experience > 5
end
def relations
GradeLevel.all.select do |record|
if(record.teacher_id == self.id)
record
end
end
end
def students_taught
relations.map do |record|
Student.find do |student|
student.id == record.student_id
end
end
end
def grades_taught
students_taught.map do |student|
student.grade_level
end.uniq
end
end |
module AppBuilder
def self.included(base)
base.extend(ClassMethods)
end
[:builder, :stdout, :stderr, :build!].each do |meth|
define_method(meth) do |*args|
self.class.send(meth, *args)
end
end
def app_exec(cmd)
container = builder.image.run("/exec #{cmd}")
container.wait
container.logs(stdout: true, stdin: true)
.gsub(/[\u0000-\u0010]/, "")
ensure
container.remove(force: true) if container
end
def app_start(proc)
container = builder.image.run("/start #{proc}")
yield container
container.stop
ensure
container.remove(force: true) if container
end
def try_exec(container, cmd, timeout)
Timeout.timeout(timeout) do
loop do
out, err, status = container.exec(cmd)
return out, err if status == 0
sleep 1
end
end
end
module ClassMethods
def build!(app)
@test_app = app
log # just force load log
end
def builder
@builder ||= Hodor::Builder.new(File.expand_path("../../apps/#{@test_app}", __FILE__))
end
def log
@log ||= CaptureIO.verbose do
builder.build
end
end
def stdout
log[0]
end
def stderr
log[1]
end
end
end
|
# frozen_string_literal: true
# == Schema Information
#
# Table name: books
#
# id :bigint(8) not null, primary key
# base_price :integer
# image_content_type :string
# image_file_name :string
# image_file_size :integer
# image_updated_at :datetime
# release_date :date
# title :string
# created_at :datetime not null
# updated_at :datetime not null
# format_id :bigint(8)
#
# Indexes
#
# index_books_on_format_id (format_id)
#
# Class for books
class Book < ApplicationRecord
belongs_to :format
delegate :name, to: :format, prefix: true
scope :hard_cover, -> { joins(:format).where('formats.name = ?', 'Hardcover') }
has_many :book_authors, dependent: :destroy
has_many :authors, through: :book_authors
accepts_nested_attributes_for :book_authors
validates :title, :image, presence: true
validates :base_price, presence: true, if: :valid_release_date?
has_attached_file :image
validates_attachment :image, content_type: { content_type: ['image/jpg', 'image/jpeg', 'image/png', 'image/gif'] }
def valid_release_date?
release_date? && (release_date < Date.today + 2.months)
end
def author_id
authors.first.id if authors.present?
end
end
|
class Deal < ApplicationRecord
belongs_to :brewery
belongs_to :client
end
|
# -*- encoding : utf-8 -*-
require 'spec_helper'
describe Category do
let(:category) { FactoryGirl.create(:category) }
let(:issued_category) { FactoryGirl.create(:issued_category) }
subject { category }
it { should have_many(:articles) }
it { should have_many(:navigators).dependent(:destroy) }
it { should validate_presence_of(:name) }
it { should validate_uniqueness_of(:permalink) }
it "should fetch issued categories" do
Category.issued.should include(issued_category)
Category.issued.should_not include(category)
end
it "should fetch non issued categories" do
Category.non_issued.should include(category)
Category.non_issued.should_not include(issued_category)
end
end
|
require 'spec_helper'
describe 'sensu::repo', :type => :class do
it { should create_class('sensu::repo') }
['Debian', 'Ubuntu' ].each do |os|
describe "operatingsystem: #{os}" do
let(:facts) { { :operatingsystem => os } }
context 'no params' do
it { should contain_class('sensu::repo::apt').with_ensure('present') }
end
['present', 'absent'].each do |state|
context "ensure: #{state}" do
let(:params) { { :ensure => state } }
it { should contain_class('sensu::repo::apt').with_ensure(state) }
end
end
end
end
['Rhel', 'CentOS' ].each do |os|
describe "operatingsystem: #{os}" do
let(:facts) { { :operatingsystem => os } }
context 'no params' do
it { should contain_class('sensu::repo::yum').with_ensure('present') }
end
['present', 'absent'].each do |state|
context "ensure: #{state}" do
let(:params) { { :ensure => state } }
it { should contain_class('sensu::repo::yum').with_ensure(state) }
end
end
end
end
describe 'operatingsystem: Darwin' do
let(:facts) { { :operatingsystem => 'Darwin' } }
context 'no params' do
it { expect { should raise_error(Puppet::Error) } }
end
['present', 'absent'].each do |state|
context "ensure => #{state}" do
let(:params) { { :ensure => state } }
it { expect { should raise_error(Puppet::Error) } }
end
end
end
end
|
# == Schema Information
#
# Table name: users
#
# id :integer not null, primary key
# name :string(255)
# email :string(255)
# created_at :datetime not null
# updated_at :datetime not null
# password_digest :string(255)
# remember_token :string(255)
# admin :boolean default(FALSE)
#
# Indexes
#
# index_users_on_email (email) UNIQUE
# index_users_on_remember_token (remember_token)
#
require 'spec_helper'
describe User do
let(:user) { create(:user) }
subject { user }
specify "model attributes" do
should respond_to(:name)
should respond_to(:email)
should respond_to(:password_digest)
should respond_to(:remember_token)
should respond_to(:admin)
end
specify "accessible attributes" do
should_not allow_mass_assignment_of(:password_digest)
should_not allow_mass_assignment_of(:remember_token)
should_not allow_mass_assignment_of(:admin)
end
specify "associations" do
should have_many(:microposts).dependent(:destroy)
should have_many(:active_relationships)
.class_name("Relationship")
.dependent(:destroy)
should have_many(:followed_users).through(:active_relationships)
should have_many(:passive_relationships)
.class_name("Relationship")
.dependent(:destroy)
should have_many(:followers).through(:passive_relationships)
end
specify "virtual attributes/methods from has_secure_password" do
should respond_to(:password)
should respond_to(:password_confirmation)
should respond_to(:authenticate)
end
specify "instance methods" do
should respond_to(:feed).with(0).arguments
should respond_to(:following?).with(1).argument
should respond_to(:follow!).with(1).argument
should respond_to(:unfollow!).with(1).argument
end
describe "class level" do
subject { user.class }
specify "methods" do
should respond_to(:authenticate).with(2).arguments
end
end
describe "initial state" do
it { should be_valid }
it { should_not be_admin }
its(:remember_token) { should_not be_blank }
its(:email) { should_not =~ %r(\p{Upper}) }
end
describe "validations" do
context "for name" do
it { should validate_presence_of(:name) }
it { should_not allow_value(" ").for(:name) }
it { should ensure_length_of(:name).is_at_most(50) }
end
context "for email" do
it { should validate_presence_of(:email) }
it { should_not allow_value(" ").for(:email) }
it { should validate_uniqueness_of(:email).case_insensitive }
context "when email format is invalid" do
invalid_email_addresses.each do |invalid_address|
it { should_not allow_value(invalid_address).for(:email) }
end
end
context "when email format is valid" do
valid_email_addresses.each do |valid_address|
it { should allow_value(valid_address).for(:email) }
end
end
end
context "for password" do
it { should validate_presence_of(:password) }
it { should ensure_length_of(:password).is_at_least(6) }
it { should_not allow_value(" ").for(:password) }
context "when password doesn't match confirmation" do
it { should_not allow_value("mismatch").for(:password) }
end
end
context "for password_confirmation" do
it { should validate_presence_of(:password_confirmation) }
end
end
context "when admin attribute set to 'true'" do
before { user.toggle!(:admin) }
it { should be_admin }
end
describe "#authenticate from has_secure_password" do
let(:found_user) { User.find_by_email(user.email) }
context "with valid password" do
it { should == found_user.authenticate(user.password) }
end
context "with invalid password" do
let(:user_with_invalid_password) { found_user.authenticate("invalid") }
it { should_not == user_with_invalid_password }
specify { user_with_invalid_password.should be_false }
end
end
describe "micropost associations" do
let!(:older_micropost) do
create(:micropost, user: user, created_at: 1.day.ago)
end
let!(:newer_micropost) do
create(:micropost, user: user, created_at: 1.hour.ago)
end
context "ordered by microposts.created_at DESC" do
subject { user.microposts }
it { should == [newer_micropost, older_micropost] }
end
context "when user is destroyed" do
subject { -> { user.destroy } }
it { should change(Micropost, :count).by(-2) }
end
describe "status" do
let(:unfollowed_post) { create(:micropost, user: create(:user)) }
let(:followed_user) { create(:user) }
before do
user.follow!(followed_user)
3.times { followed_user.microposts.create!(content: "Lorem Ipsum") }
end
its(:feed) { should include(newer_micropost) }
its(:feed) { should include(older_micropost) }
its(:feed) { should_not include(unfollowed_post) }
its(:feed) do
followed_user.microposts.each do |micropost|
should include(micropost)
end
end
end
end
describe "#follow!" do
let(:other_user) { create(:user) }
before { user.follow!(other_user) }
it { should be_following(other_user) }
its(:followed_users) { should include(other_user) }
describe "#unfollow!" do
before { user.unfollow!(other_user) }
it { should_not be_following(other_user) }
its(:followed_users) { should_not include(other_user) }
end
describe "followed user" do
subject { other_user }
its(:followers) { should include(user) }
end
end
describe "relationship associations" do
let(:other_user) { create(:user) }
before do
user.follow!(other_user)
other_user.follow!(user)
end
context "when user is destroyed" do
describe "behaviour" do
before { user.destroy }
its(:active_relationships) { should be_empty }
its(:passive_relationships) { should be_empty }
end
describe "result" do
subject { -> { user.destroy } }
it { should change(Relationship, :count).by(-2) }
end
end
context "when a follower/followed user is destroyed" do
describe "behaviour" do
subject { other_user }
before { user.destroy }
its(:active_relationships) { should_not include(user) }
its(:passive_relationships) { should_not include(user) }
end
describe "result" do
subject { -> { user.destroy } }
it { should change(Relationship, :count).by(-2) }
end
end
end
end
|
# frozen_string_literal: true
class CourseCategoriesController < ApplicationController
before_action :set_course_category, only: %i[show edit update destroy]
def index
@course_categories = CourseCategory.all
end
def show; end
def new
@course_category = CourseCategory.new
end
def edit; end
def create
@course_category = CourseLecture.new(course_category_params)
respond_to do |format|
if @course_category.save
format.html { redirect_to @course_category, notice: 'Course lecture was successfully created.' }
format.json { render :show, status: :created, location: @course_category }
else
format.html { render :new, status: :unprocessable_entity }
format.json { render json: @course_category.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /course_categorys/1 or /course_categorys/1.json
def update
respond_to do |format|
if @course_category.update(course_category_params)
format.html { redirect_to @course_category, notice: 'Course lecture was successfully updated.' }
format.json { render :show, status: :ok, location: @course_category }
else
format.html { render :edit, status: :unprocessable_entity }
format.json { render json: @course_category.errors, status: :unprocessable_entity }
end
end
end
# DELETE /course_categorys/1 or /course_categorys/1.json
def destroy
@course_category.destroy
respond_to do |format|
format.html { redirect_to course_lectures_url, notice: 'Course lecture was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_course_category
@course_category = CourseCategory.find(params[:id])
end
# Only allow a list of trusted parameters through.
def course_category_params
params.require(:course_category).permit(:name)
end
end
|
class DeckCard < ApplicationRecord
belongs_to :deck
belongs_to :card
validates_inclusion_of :quantity, in: 1..3
end
|
module Fog
module Compute
class Google
class Snapshot < Fog::Model
identity :name
attribute :creation_timestamp, :aliases => "creationTimestamp"
attribute :description
attribute :disk_size_gb, :aliases => "diskSizeGb"
attribute :id
attribute :kind
attribute :label_fingerprint, :aliases => "labelFingerprint"
attribute :labels
attribute :licenses
attribute :self_link, :aliases => "selfLink"
attribute :snapshot_encryption_key, :aliases => "snapshotEncryptionKey"
attribute :source_disk, :aliases => "sourceDisk"
attribute :source_disk_encryption_key, :aliases => "sourceDiskEncryptionKey"
attribute :source_disk_id, :aliases => "sourceDiskId"
attribute :status
attribute :storage_bytes, :aliases => "storageBytes"
attribute :storage_bytes_status, :aliases => "storageBytesStatus"
CREATING_STATE = "CREATING".freeze
DELETING_STATE = "DELETING".freeze
FAILED_STATE = "FAILED".freeze
READY_STATE = "READY".freeze
UPLOADING_STATE = "UPLOADING".freeze
def destroy(async = true)
requires :identity
data = service.delete_snapshot(identity)
operation = Fog::Compute::Google::Operations.new(:service => service)
.get(data.name)
operation.wait_for { ready? } unless async
operation
end
def set_labels(new_labels)
requires :identity, :label_fingerprint
unless new_labels.is_a? Hash
raise ArgumentError,
"Labels should be a hash, e.g. {foo: \"bar\",fog: \"test\"}"
end
service.set_snapshot_labels(identity, label_fingerprint, new_labels)
reload
end
def ready?
status == READY_STATE
end
def resource_url
"#{service.project}/global/snapshots/#{name}"
end
end
end
end
end
|
class Contact < ActionMailer::Base
def from_site(contact, receive_a_copy = false)
common_settings(contact.subject || "Contato via Dev in Sampa", contact.email)
recipients "contato@devinsampa.com.br"
cc contact.email if receive_a_copy
body :contact => contact
end
def attendee_created(attendee)
common_settings "Confirmação de inscrição"
recipients attendee.email
from "devinsampa@gmail.com"
body :name => attendee.name, :link => payment_url(:token => attendee.token), :free => attendee.free?, :doc => attendee.doc
end
def attendee_confirmation(attendee)
common_settings "Confirmação de pagamento"
recipients attendee.email
body :name => attendee.name, :doc => attendee.doc
end
def attendee_pending(attendee)
status = {:pending => "Aguardando pagamento", :verifying => "Em análise"}
common_settings "Aguardando confirmação de pagamento pelo PagSeguro"
recipients attendee.email
body :status => status[attendee.status], :name => attendee.name, :link => payment_url(:token => attendee.token)
end
def attendee_problem(attendee)
status = {:canceled => "Cancelado", :refunded => "Devolvido"}
common_settings "Problemas no pagamento da inscrição"
recipients attendee.email
body :status => status[attendee.status], :name => attendee.name, :link => payment_url(:token => attendee.token)
end
def attendee_unregister(attendee)
common_settings "Cancelamento de inscrição"
recipients attendee.email
body :attendee => attendee
end
def attendee_will_unregister(attendee)
common_settings "Sua inscrição será cancelada"
recipients attendee.email
body :name => attendee.name, :link => payment_url(:token => attendee.token)
end
def alert_us(notification, request, params)
common_settings "Algum esperto querendo fazer baixa em nome do PagSeguro"
recipients "all@devinsampa.com.br"
body :notification => notification.inspect, :request => request.inspect, :params => params.inspect
end
private
def common_settings(subject_, replying_to = "contato@devinsampa.com.br")
default_url_options[:host] = "www.devinsampa.com.br"
from "devinsampa@gmail.com"
subject "[devinsampa] #{subject_}"
reply_to replying_to
end
end
|
module ServiceOffering
class Icons
attr_reader :icon_id
attr_reader :icon
def initialize(id)
@icon_id = id.to_s
end
def process
TopologicalInventory.call do |api_instance|
@icon = api_instance.show_service_offering_icon(@icon_id)
end
self
rescue StandardError => e
Rails.logger.error("Portfolio Item Icons ID #{@icon_id}: #{e.message}")
raise
end
end
end
|
class CreateProducts < ActiveRecord::Migration[5.2]
def change
create_table :products do |t|
t.string :name, null: false, index: true
t.string :detail, null: false, index: true
t.integer :size_id, null: false
t.integer :price, null: false
t.integer :status_id, default: 0
t.integer :condition_id, null: false
t.integer :shippingaddress_id, null: false
t.integer :shippingdate_id, null: false
t.string :buyer, default: ""
t.string :seller
t.integer :payer_id, null: false
t.references :user, null: false, foreign_key: true
t.references :category, null: false, foreign_key: true
t.timestamps
end
end
end
|
class RemoveLengthFromPrograms < ActiveRecord::Migration
def change
remove_column :programs, :length, :time
end
end
|
# == Schema Information
# Schema version: 20110309094442
#
# Table name: tags
#
# id :integer not null, primary key
# name :string(255)
# document_id :integer
# created_at :datetime
# updated_at :datetime
#
class Tag < ActiveRecord::Base
attr_accessible :name, :document_id
belongs_to :document
validates_presence_of :name
validates_length_of :name, :maximum => 20
validates_uniqueness_of :name, :scope => :document_id
end
|
FactoryBot.define do
factory :offer do
advertiser_name {'Advertiser Name'}
url {'http://some.url.com'}
description {'A little description'}
starts_at {Date.today}
ends_at {Date.today + 3.days}
premium {true}
end
end
|
module Warren
class Client
TYPES = [:disk, :ram]
attr_reader :hostname, :node_name, :type, :cluster
attr_reader :address # name@hostname
attr_reader :adapter
def initialize(adapter: , hostname: adapter.hostname, node_name: Warren.config.node_name, type: Node::TYPES.first)
@node_name = node_name
@adapter = adapter
@hostname = hostname
@type = type
@address = "#{@node_name}@#{@hostname}"
setup_env
`hostname #{ENV['HOSTNAME']}`
`echo "127.0.0.1 #{ENV['HOSTNAME']}" >> /etc/hosts`
end
def setup_env
ENV.tap do |e|
e['RABBITMQ_USE_LONGNAME'] = 'true'
e['HOSTNAME'] = hostname
e['RABBITMQ_NODENAME'] = address
e['MNESIA_NODE_BASE_DIR'] = Warren.config.base_mnesia_dir
e['RABBITMQ_LOG_BASE'] = Warren.config.log_base
# TODO: Make configurable?
e['RABBITMQ_MNESIA_DIR'] = "#{e['MNESIA_NODE_BASE_DIR']}/#{node_name}"
e['RABBITMQ_LOGS'] = "#{e['RABBITMQ_LOG_BASE']}/#{e['RABBITMQ_NODENAME']}.info"
e['RABBITMQ_SASL_LOGS'] = "#{e['RABBITMQ_LOG_BASE']}/#{e['RABBITMQ_NODENAME']}-sasl.info"
end
end
def pid_file
"#{ENV['MNESIA_NODE_BASE_DIR']}/#{ENV['node_name']}.pid"
end
def apply_policies
Warren.config.policies.each do |policy_name, schema|
target = schema['target'] || 'all'
pattern = schema['pattern'] || '.*'
policy_hash = schema['policy'] || {}
policy = "{#{policy_hash.collect { |k, v| "\"#{k}\":\"#{v}\"" }.join(", ")}}"
base_cmd = "--apply-to #{target} #{policy_name} \"#{pattern}\" '#{policy}'"
Warren.logger.info "Applying policy #{base_cmd}"
set_policy(base_cmd)
end
end
def cluster_with(cluster: nil, nodes: [])
Warren.logger.error("Specify at least one node to cluster with.") and return if nodes.empty?
stop_app
nodes.each do |node|
begin
node_address = "#{Warren.config.node_name}@#{node}"
cluster_status = Node.status(address: node_address)
response = RabbitMQ.ctl("-n #{@address} join_cluster #{node_address}", log: :info)
cluster_name=(cluster) unless cluster.nil?
return true
rescue RabbitMQ::InconsistentCluster => e
Warren.logger.error(e.message)
Warren.logger.info RabbitMQ.ctl("-n #{node_address} forget_cluster_node #{@address}", log: :info)
sleep 5
retry
rescue RabbitMQ::Nodedown => e
Warren.logger.warn("Node down. Skipping...")
Warren.logger.warn(e.message)
# TODO: Clean up that node
next
rescue RabbitMQ::Exception => e
Warren.logger.error(e.message)
else
break
end
end
end
def healthy?
# health.match(/nodedown/)
end
[
:start_app,
:stop_app,
:start_server,
:stop_server,
:clustered?,
:cluster_name,
:set_policy,
:clustered_with?,
:status,
:cleanup,
:cluster_name=
].each do |meth|
define_method(meth) do |*args, **keyword_args|
Node.send(meth, *args, address: @address, **keyword_args)
end
end
end
end
|
module SerializerHelper
# Serializing object
def serialize(object, context=nil)
klass = convert_to_resource_class(object)
JSONAPI::ResourceSerializer.new(klass).serialize_to_hash(klass.new(object, context))
end
private
def convert_to_resource_class (object)
Object.const_get("Api::V1::#{object.class.to_s}Resource")
end
end |
module Synapse
module RetryPolicy
include Synapse::StatsD
def with_retry(options = {}, &callback)
max_attempts = options['max_attempts'] || 1
max_delay = options['max_delay'] || 3600
base_interval = options['base_interval'] || 0
max_interval = options['max_interval'] || 0
retriable_errors = Array(options['retriable_errors'] || StandardError)
if max_attempts <= 0
raise ArgumentError, "max_attempts must be greater than 0"
end
if base_interval < 0
raise ArgumentError, "base_interval cannot be negative"
end
if max_interval < 0
raise ArgumentError, "max_interval cannot be negative"
end
if base_interval > max_interval
raise ArgumentError, "base_interval cannot be greater than max_interval"
end
if callback.nil?
raise ArgumentError, "callback cannot be nil"
end
attempts = 0
start_time = Time.now
begin
attempts += 1
return callback.call(attempts)
rescue *retriable_errors => error
if attempts >= max_attempts
statsd_increment('synapse.retry', ['op:raise_max_attempts'])
raise error
end
if (Time.now - start_time) >= max_delay
statsd_increment('synapse.retry', ['op:raise_max_delay'])
raise error
end
statsd_increment('synapse.retry', ['op:retry_after_sleep'])
sleep get_retry_interval(base_interval, max_interval, attempts)
retry
end
end
def get_retry_interval(base_interval, max_interval, attempts)
retry_interval = base_interval * (2 ** (attempts - 1)) # exponetial back-off
retry_interval = retry_interval * (0.5 * (1 + rand())) # randomize
[[retry_interval, base_interval].max, max_interval].min # regularize
end
end
end
|
require("spec_helper")
describe("Specialty") do
describe(".all") do
it("starts off with no specialties") do
expect(Specialty.all()).to(eq([]))
end
end
describe("#name") do
it("tells you the specialty's name") do
specialty = Specialty.new({:name => "Orthopedics", :id => nil})
expect(specialty.name()).to(eq("Orthopedics"))
end
end
describe("#id") do
it("sets specialty's ID when you save it") do
specialty = Specialty.new({:name => "Orthopedics", :id => nil})
specialty.save()
expect(specialty.id()).to(be_an_instance_of(Fixnum))
end
end
describe("#save") do
it("lets you save the specialty to the database") do
specialty = Specialty.new({:name => "Optometry", :id => nil})
specialty.save()
expect(Specialty.all()).to(eq([specialty]))
end
end
describe("#==") do
it("is the same specialty if it has the same name and id") do
specialty1 = Specialty.new({:name => "Optometry", :id => nil})
specialty2 = Specialty.new({:name => "Optometry", :id => nil})
expect(specialty1).to(eq(specialty2))
end
end
#
describe(".find") do
it("returns a specialty by its ID") do
specialty1 = Specialty.new({:name => "Optometry", :id => nil})
specialty1.save()
specialty2 = Specialty.new({:name => "Neurosurgery", :id => nil})
specialty2.save()
expect(Specialty.find(specialty2.id())).to(eq(specialty2))
end
end
describe("#doctors") do
it("returns an array of doctors for that specialty") do
test_specialty = Specialty.new({:name => "Optometry", :id => nil})
test_specialty.save()
test_doctor = Doctor.new({:name => "Dr. Andrews", :specialty => "Optometry", :specialty_id => test_specialty.id(), :id => nil})
test_doctor.save()
test_doctor2 = Doctor.new({:name => "Dr. Carter", :specialty => "Optometry", :specialty_id => test_specialty.id(), :id => nil})
test_doctor2.save()
expect(test_specialty.doctors(test_specialty.id())).to(eq([test_doctor, test_doctor2]))
end
end
end
|
class AddDefaultToPauseCountInAccountDetail < ActiveRecord::Migration[5.1]
def change
remove_column :account_details, :pause_permit_count, :integer
add_column :account_details, :pause_permit_count, :integer, default: 0
end
end
|
class AlterMovementAddSchoolId < ActiveRecord::Migration
def change
add_column :movements, :school_id, :integer
add_index :movements, :school_id
end
end
|
# Generates help pages to be loaded into application’s built-in Help window.
# Generates pages from docs collection, but sets an extra frontmatter variable
# ``in_app_help: true`` for each page.
#
# Note: “docs” below can be used to refer to documentation pages
# as well as to Jekyll’s concept of “document”.
module Jekyll
class InAppHelpPage < Page
def initialize(site, base_dir, url_prefix, path, content, data)
@site = site
@base = base_dir
url_prefix = site.config['in_app_help']['url_prefix']
if path.end_with?('/index')
@dir = url_prefix
else
@dir = File.join(url_prefix, path)
end
@content = content
@name = "index.html"
self.process(@name)
self.data = data.clone
self.data['in_app_help'] = site.config['in_app_help']
self.data['permalink'] = nil
self.data['site_title'] = "#{site.config['in_app_help']['app_name']} Help"
end
end
class Site
def write_in_app_help_pages(in_collection, url_prefix)
originals = @collections[in_collection]
originals.docs.each do |doc|
if doc.data['permalink']
permalink = doc.data['permalink'].sub("/#{in_collection}/", '')
else
permalink = doc.cleaned_relative_path
end
page = InAppHelpPage.new(self, self.source, url_prefix, permalink, doc.content, doc.data)
@pages << page
end
end
end
end
Jekyll::Hooks.register :site, :post_read do |site|
if site.config.key?('in_app_help')
cfg = site.config['in_app_help']
site.write_in_app_help_pages(
cfg['in_collection'],
cfg['url_prefix'])
end
end
|
module VagrantPlugins
module Beaker
module Command
class TestRunnerConfig < Vagrant.plugin( 2, :config )
def initialize
@tests = UNSET_VALUE
@helper = UNSET_VALUE
end
def tests=( one_or_more_tests )
@tests = Array( one_or_more_tests )
end
def tests
@tests
end
def helper
@helper
end
def helper=( one_or_more_helpers )
@helper = Array( one_or_more_helpers )
end
def merge( other )
super.tap do |result|
result.tests = tests | other.tests
result.helper = helper | other.helper
end
end
def finalize!
@tests = [] if @tests == UNSET_VALUE
@helper = [] if @helper == UNSET_VALUE
end
def validate( machine )
{}
end
end
end
end
end
|
class CreateNearbyEvents < ActiveRecord::Migration[5.1]
def change
create_table :nearby_events do |t|
t.integer :user_id, null: false
t.decimal :lat, null: false, precision: 10, scale: 6
t.decimal :lng, null: false, precision: 10, scale: 6
t.date :date, null: false
t.time :start_time, null: false
t.time :end_time, null: false
t.text :description
t.integer :current_players
t.integer :max_players
t.text :current_setup
t.string :photo
t.timestamps
end
add_index :nearby_events, :user_id, unique: true
end
end
|
class BlogsController < ApplicationController
before_action :set_blog, only: [:show, :comment]
def index
@blogs = Blog.order(id: :desc).page(params[:page]).per(params[:per_page])
end
def new
@blog = Blog.new
end
def show
@comments = @blog.comments.page(params[:page]).per(params[:per_page])
end
def create
@blog = Blog.new(blog_params)
if @blog.save
flash[:success] = '创建成功'
redirect_to blogs_path
else
flash[:error] = "创建失败,#{@blog.errors.full_messages}"
render "new"
end
end
def comment
@comment = @blog.comments.new(comment_params.merge(user_id: current_user.id))
if @comment.save
flash[:success] = '创建成功'
redirect_to blog_path(@blog)
else
flash[:error] = "创建失败,#{@comment.errors.full_messages}"
render "new"
end
end
private
def blog_params
params.require(:blog).permit(:title, :content)
end
def comment_params
params.require(:comment).permit(:content)
end
def set_blog
@blog = Blog.find(params[:id])
end
end
|
class Comment < ActiveRecord::Base
belongs_to :photo
has_many :likes
end
|
Airbrake.configure do |config|
config.environment = Rails.env
config.ignore_environments = %w(development test)
config.project_id = 1
config.project_key = ENV.fetch('ERRBIT_PROJECT_KEY', '_')
config.host = ENV.fetch('ERRBIT_URL', '')
end
|
require 'socket'
require 'openssl'
require_relative 'events'
class SocketClient
def initialize e
@e = e
@debug = true
@sockets = []
end
def Create name, host, port, ssl
sock = TCPSocket.open(host, port)
sock.setsockopt(Socket::SOL_SOCKET, Socket::SO_KEEPALIVE, true)
if ssl
ssl_context = OpenSSL::SSL::SSLContext.new
ssl_context.verify_mode = OpenSSL::SSL::VERIFY_NONE
sock = OpenSSL::SSL::SSLSocket.new(sock, ssl_context)
sock.sync = true
sock.connect
end
if sock
hash = {"name" => name, "host" => host, "port" => port, "ssl" => ssl, "socket" => sock}
@sockets = [] if @sockets.nil?
@sockets.push(hash)
@e.Run "ConnectionCompleted", name, sock
end
end
def CheckForNewData
if !@sockets.nil?
@sockets.each { |hash|
name = hash["name"]
ssl = hash["ssl"]
sock = hash["socket"]
begin
# This is an IRC specific thing and *not* RPS.
# This will be fixed at some point.
data = sock.gets("\r\n") if ssl
data = sock.gets("\r\n") if !ssl
rescue IO::WaitReadable
end
if data.is_a?(String)
dataline = data.split("\r\n")
dataline.each { |line|
line = line.to_s.chomp
time = Time.now
puts "[~R] [#{name}] [#{time.strftime("%Y-%m-%d %H:%M:%S")}] #{line}" if @debug
@e.Run "NewData", name, sock, line
}
end
data = nil
line = nil
dataline = nil
}
end
end
def Get name
@sockets.each { |socket| return socket["sock"] if socket["name"] == name }
return false
end
end # End Class "SocketClient"
|
class UnknownMessagesController < ApplicationController
load_and_authorize_resource
def index
@messages = UnknownMessage.all
respond_to do |format|
format.html # show.html.erb
format.json { render json: @messages }
end
end
def destroy
@message = UnknownMessage.find(params[:id])
@message.destroy
respond_to do |format|
format.html { redirect_to unknown_messages_path, notice: 'Message has been successfully deleted.' }
format.json { head :no_content }
end
end
end
|
# -*- encoding: utf-8 -*-
Gem::Specification.new do |s|
s.version = "0.6.6"
s.name = 'pyrite'
s.summary = 'Easy peasy browser testing'
s.description = 'A small, simple testing framework for use with selenium'
s.authors = ["Adam Rogers","Dean Strelau"]
s.email = 'adam@mintdigital.com'
s.homepage = 'http://mintdigital.github.com/pyrite'
s.files = Dir["{lib,tasks}/**/*"] + %w[MIT-LICENSE README.rdoc]
s.require_paths = ["lib"]
s.add_runtime_dependency 'selenium-client', '~> 1.2.18'
s.add_runtime_dependency 'selenium_remote_control', '~> 1.0.4'
s.add_runtime_dependency 'database_cleaner', '~> 0.5.2'
end
|
class Hour < ActiveRecord::Base
belongs_to :user
belongs_to :project
belongs_to :hourtype
validates :user_id, numericality: true
validates :project_id, numericality: true
validates :hourtype_id, numericality: true
validates :date, presence: true
validates :duration_human, presence: true
validates :duration, presence: true, numericality: true
validate :valid_duration
validates :description, presence: true, length: { maximum: 256, minimum: 5 }
def duration_human=(d)
write_attribute( :duration_human, d )
if( sec = seconds_in(d) )
write_attribute( :duration, sec )
else
write_attribute( :duration, 0 )
end
end
def valid_duration
errors.add(:duration_human, "Wat do you think! This is noncence!!!, try 1h, 1hour whatever" ) if seconds_in( duration_human ) == false
end
private
def seconds_in(time)
now = Time.now
seconds = ChronicDuration.parse( time )
parsed = Chronic.parse("#{seconds} seconds from now", :now => now)
if( parsed )
parsed - now
else
false
end
end
end
|
require "spec_helper"
describe Lob::Resources::Area do
before :each do
@sample_area_params = {
description: "Test Area",
front: "https://s3-us-west-2.amazonaws.com/lob-assets/areafront.pdf",
back: "https://s3-us-west-2.amazonaws.com/lob-assets/areaback.pdf",
routes: ["94158-C001", "94107-C031"],
}
end
subject { Lob::Client.new(api_key: API_KEY) }
describe "list" do
it "should list areas" do
assert subject.areas.list["object"] == "list"
end
end
describe "create" do
it "should create an area object" do
result = subject.areas.create @sample_area_params
result["object"].must_equal("area")
end
it "should create an area object with optionals params" do
@sample_area_params[:target_type] = "all"
result = subject.areas.create @sample_area_params
result["description"].must_equal @sample_area_params[:description]
end
it "should create an area object with a single route" do
@sample_area_params[:routes] = "94158-C001"
result = subject.areas.create @sample_area_params
result["object"].must_equal("area")
end
it "should create an area object with zip_codes" do
@sample_area_params[:routes] = ["94158"];
result = subject.areas.create @sample_area_params
result["object"].must_equal("area")
end
end
describe "find" do
it "should find an area" do
new_area = subject.areas.create @sample_area_params
result = subject.areas.find new_area["id"]
result["object"].must_equal("area")
end
end
end
|
class Divingsite < ApplicationRecord
belongs_to :country
has_many :reviews, dependent: :destroy
has_many :reviews
acts_as_votable
has_attached_file :divesiteimage, default_url: "/images/:style/missing.png"
validates_attachment_content_type :divesiteimage, content_type: /\Aimage\/.*\z/
def self.search(search)
where("name LIKE ?", "%#{search}%")
end
def rating_average
review_ratings = []
if self.reviews.count == 0
return 0
else
self.reviews.each do |review|
review_ratings << review.rating
end
end
review_ratings.inject(0.0) { |sum, el| sum + el } / review_ratings.size
end
def self.top
Divingsite.all.max_by do |divingsite|
divingsite.rating_average
end
end
def self.topfive
Divingsite.all.max_by(5) do |divingsite|
divingsite.rating_average
end
end
end
|
module Slack
module Aria
class Akari < Undine
class << self
def name
'水無灯里'
end
def icon
'https://raw.githubusercontent.com/takesato/slack-aria/master/image/akari120x120.jpg'
end
end
Company.client.on :message do |data|
if data['type'] == 'message' && rand(100) == 0 && data['subtype'] != 'bot_message'
answer = (rand(10) != 0) ? "はひっ" : "えーっ"
Akari.speak(data['channel'], "<@#{data['user']}> #{answer}")
end
end
end
end
end
|
require 'rails_helper'
RSpec.describe Ship do
describe "initialize ship" do
let(:position) { ["A", 5] }
let(:ship) { Ship.new(position.first, position.last) }
it "has size" do
expect(ship.size).not_to be nil
end
it "has position" do
expect(ship.col).to eq position.last
end
end
describe "shoot ship" do
let(:ship) { Ship.new("B", 5) }
it "hits ship" do
expect(Ship.shoot(ship, "B", 6)).to be true
end
it "misses ship" do
expect(Ship.shoot(ship, "B", 10)).to be false
end
end
end
|
require 'compiler_helper'
module Alf
class Compiler
describe Default, "unwrap" do
subject{
compiler.call(expr)
}
let(:expr){
unwrap(an_operand(leaf), :a)
}
it_should_behave_like "a traceable compiled"
it 'has a Unwrap cog' do
expect(subject).to be_kind_of(Engine::Unwrap)
end
it 'has the correct unwrapping attribute' do
expect(subject.attribute).to eq(:a)
end
it 'has the correct sub-cog' do
expect(subject.operand).to be(leaf)
end
end
end
end
|
require 'spec_helper'
describe Admin::UsersController do
it 'should deny acces to regular users' do
sign_in Factory(:user)
get :index
response.should be_redirect
end
context "as an admin user" do
before(:each) do
@admin_user = Factory(:admin)
sign_in @admin_user
end
it 'should grant acces' do
get :index
assigns(:users)
end
it "should be able to toggle a user as an expert" do
put :toggle_expert, :id => @admin_user.id
@admin_user.reload.is_expert.should == true
put :toggle_expert, :id => @admin_user.id
@admin_user.reload.is_expert.should == false
end
end
end
|
# Copyright 2014 Cognitect. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS-IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
module Transit
# Transit::Writer marshals Ruby objects as transit values to an output stream.
# @see https://github.com/cognitect/transit-format
class Writer
# @api private
class Marshaler
def initialize(opts)
@cache_enabled = !opts[:verbose]
@prefer_strings = opts[:prefer_strings]
@max_int = opts[:max_int]
@min_int = opts[:min_int]
handlers = WriteHandlers::DEFAULT_WRITE_HANDLERS.dup
handlers = handlers.merge!(opts[:handlers]) if opts[:handlers]
@handlers = (opts[:verbose] ? verbose_handlers(handlers) : handlers)
@handlers.values.each do |h|
if h.respond_to?(:handlers=)
h.handlers=(@handlers)
end
end
end
def find_handler(obj)
obj.class.ancestors.each do |a|
if handler = @handlers[a]
return handler
end
end
nil
end
def verbose_handlers(handlers)
handlers.each do |k, v|
if v.respond_to?(:verbose_handler) && vh = v.verbose_handler
handlers.store(k, vh)
end
end
handlers
end
def escape(s)
if s.start_with?(SUB,ESC,RES) && s != "#{SUB} "
"#{ESC}#{s}"
else
s
end
end
def emit_nil(as_map_key, cache)
as_map_key ? emit_string(ESC, "_", nil, true, cache) : emit_value(nil)
end
def emit_string(prefix, tag, value, as_map_key, cache)
encoded = "#{prefix}#{tag}#{value}"
if @cache_enabled && cache.cacheable?(encoded, as_map_key)
emit_value(cache.write(encoded), as_map_key)
else
emit_value(encoded, as_map_key)
end
end
def emit_boolean(handler, b, as_map_key, cache)
as_map_key ? emit_string(ESC, "?", handler.string_rep(b), true, cache) : emit_value(b)
end
def emit_int(tag, i, as_map_key, cache)
if as_map_key || i > @max_int || i < @min_int
emit_string(ESC, tag, i, as_map_key, cache)
else
emit_value(i, as_map_key)
end
end
def emit_double(d, as_map_key, cache)
as_map_key ? emit_string(ESC, "d", d, true, cache) : emit_value(d)
end
def emit_array(a, cache)
emit_array_start(a.size)
a.each {|e| marshal(e, false, cache)}
emit_array_end
end
def emit_map(m, cache)
emit_map_start(m.size)
m.each do |k,v|
marshal(k, true, cache)
marshal(v, false, cache)
end
emit_map_end
end
def emit_tagged_value(tag, rep, cache)
emit_array_start(2)
emit_string(ESC, "#", tag, false, cache)
marshal(rep, false, cache)
emit_array_end
end
def emit_encoded(handler, tag, obj, as_map_key, cache)
if tag.length == 1
rep = handler.rep(obj)
if String === rep
emit_string(ESC, tag, rep, as_map_key, cache)
elsif as_map_key || @prefer_strings
if str_rep = handler.string_rep(obj)
emit_string(ESC, tag, str_rep, as_map_key, cache)
else
raise "Cannot be encoded as String: " + {:tag => tag, :rep => rep, :obj => obj}.to_s
end
else
emit_tagged_value(tag, handler.rep(obj), cache)
end
elsif as_map_key
raise "Cannot be used as a map key: " + {:tag => tag, :rep => rep, :obj => obj}.to_s
else
emit_tagged_value(tag, handler.rep(obj), cache)
end
end
def marshal(obj, as_map_key, cache)
handler = find_handler(obj)
tag = handler.tag(obj)
case tag
when "_"
emit_nil(as_map_key, cache)
when "?"
emit_boolean(handler, obj, as_map_key, cache)
when "s"
emit_string(nil, nil, escape(handler.rep(obj)), as_map_key, cache)
when "i"
emit_int(tag, handler.rep(obj), as_map_key, cache)
when "d"
emit_double(handler.rep(obj), as_map_key, cache)
when "'"
emit_tagged_value(tag, handler.rep(obj), cache)
when "array"
emit_array(handler.rep(obj), cache)
when "map"
emit_map(handler.rep(obj), cache)
else
emit_encoded(handler, tag, obj, as_map_key, cache)
end
end
def marshal_top(obj, cache=RollingCache.new)
if handler = find_handler(obj)
if tag = handler.tag(obj)
if tag.length == 1
marshal(TaggedValue.new(QUOTE, obj), false, cache)
else
marshal(obj, false, cache)
end
flush
else
raise "Handler must provide a non-nil tag: #{handler.inspect}"
end
else
raise "Can not find a Write Handler for #{obj.inspect}."
end
end
end
# @api private
class BaseJsonMarshaler < Marshaler
def default_opts
{:prefer_strings => true,
:max_int => JSON_MAX_INT,
:min_int => JSON_MIN_INT}
end
def initialize(io, opts)
@oj = Oj::StreamWriter.new(io)
super(default_opts.merge(opts))
@state = []
end
def emit_array_start(size)
@state << :array
@oj.push_array
end
def emit_array_end
@state.pop
@oj.pop
end
def emit_map_start(size)
@state << :map
@oj.push_object
end
def emit_map_end
@state.pop
@oj.pop
end
def emit_value(obj, as_map_key=false)
if @state.last == :array
@oj.push_value(obj)
else
as_map_key ? @oj.push_key(obj) : @oj.push_value(obj)
end
end
def flush
# no-op
end
end
# @api private
class JsonMarshaler < BaseJsonMarshaler
def emit_map(m, cache)
emit_array_start(-1)
emit_value("^ ", false)
m.each do |k,v|
marshal(k, true, cache)
marshal(v, false, cache)
end
emit_array_end
end
end
# @api private
class VerboseJsonMarshaler < BaseJsonMarshaler
def emit_string(prefix, tag, value, as_map_key, cache)
emit_value("#{prefix}#{tag}#{value}", as_map_key)
end
def emit_tagged_value(tag, rep, cache)
emit_map_start(1)
emit_string(ESC, "#", tag, true, cache)
marshal(rep, false, cache)
emit_map_end
end
end
# @api private
class MessagePackMarshaler < Marshaler
def default_opts
{:prefer_strings => false,
:max_int => MAX_INT,
:min_int => MIN_INT}
end
def initialize(io, opts)
@io = io
@packer = MessagePack::Packer.new(io)
super(default_opts.merge(opts))
end
def emit_array_start(size)
@packer.write_array_header(size)
end
def emit_array_end
# no-op
end
def emit_map_start(size)
@packer.write_map_header(size)
end
def emit_map_end
# no-op
end
def emit_value(obj, as_map_key=:ignore)
@packer.write(obj)
end
def flush
@packer.flush
@io.flush
end
end
# @param [Symbol] format required :json, :json_verbose, or :msgpack
# @param [IO] io required
# @param [Hash] opts optional
#
# Creates a new Writer configured to write to <tt>io</tt> in
# <tt>format</tt> (<tt>:json</tt>, <tt>:json_verbose</tt>,
# <tt>:msgpack</tt>).
#
# Use opts to register custom write handlers, associating each one
# with its type.
#
# @example
# json_writer = Transit::Writer.new(:json, io)
# json_verbose_writer = Transit::Writer.new(:json_verbose, io)
# msgpack_writer = Transit::Writer.new(:msgpack, io)
# writer_with_custom_handlers = Transit::Writer.new(:json, io,
# :handlers => {Point => PointWriteHandler})
#
# @see Transit::WriteHandlers
def initialize(format, io, opts={})
@marshaler = case format
when :json
require 'oj'
JsonMarshaler.new(io,
{:prefer_strings => true,
:verbose => false,
:handlers => {}}.merge(opts))
when :json_verbose
require 'oj'
VerboseJsonMarshaler.new(io,
{:prefer_strings => true,
:verbose => true,
:handlers => {}}.merge(opts))
else
require 'msgpack'
MessagePackMarshaler.new(io,
{:prefer_strings => false,
:verbose => false,
:handlers => {}}.merge(opts))
end
end
# Converts a Ruby object to a transit value and writes it to this
# Writer's output stream.
#
# @param obj the value to write
# @example
# writer = Transit::Writer.new(:json, io)
# writer.write(Date.new(2014,7,22))
def write(obj)
@marshaler.marshal_top(obj)
end
end
end
|
require 'vanagon/component/source/git'
describe "Vanagon::Component::Source::File" do
let (:file_base) { 'file://spec/fixtures/files/fake_file_ext' }
let (:tar_filename) { 'file://spec/fixtures/files/fake_dir.tar.gz' }
let (:plaintext_filename) { 'file://spec/fixtures/files/fake_file.txt' }
let (:workdir) { Dir.mktmpdir }
let (:simple_directory) { 'file://spec/fixtures/files/fake_dir/' }
let (:nested_directory) { 'file://spec/fixtures/files/fake_nested_dir/' }
describe "#fetch" do
it "puts the source file in to the workdir" do
file = Vanagon::Component::Source::Local.new(plaintext_filename, workdir: workdir)
file.fetch
expect(File).to exist("#{workdir}/fake_file.txt")
end
it "puts the source directory in to the workdir" do
file = Vanagon::Component::Source::Local.new(simple_directory, workdir: workdir)
file.fetch
expect(File).to exist("#{workdir}/fake_dir/fake_file.txt")
end
it "preserves nested directories when copying folders" do
file = Vanagon::Component::Source::Local.new(nested_directory, workdir: workdir)
file.fetch
expect(File).to exist("#{workdir}/fake_nested_dir/fake_dir/fake_file.txt")
end
end
describe "#dirname" do
it "returns the name of the tarball, minus extension for archives" do
file = Vanagon::Component::Source::Local.new(tar_filename, workdir: workdir)
file.fetch
expect(file.dirname).to eq("fake_dir")
end
end
describe "#ref" do
it "returns the current directory for non-archive files" do
file = Vanagon::Component::Source::Local.new(plaintext_filename, workdir: workdir)
file.fetch
expect(file.dirname).to eq("./")
end
end
describe "#extension" do
it "returns the extension for valid extensions" do
Vanagon::Component::Source::Local.archive_extensions.each do |ext|
filename = "#{file_base}#{ext}"
file = Vanagon::Component::Source::Local.new(filename, workdir: workdir)
file.fetch
expect(file.extension).to eq(ext)
end
end
end
end
|
require 'kilomeasure'
describe 'showerheads' do
include_examples 'measure', 'showerheads'
let!(:before_inputs) do
{
afue: 0.7,
gpm: 2.5,
dhw_cold_water_temperature: 80,
dhw_hot_water_temperature: 130
}
end
let!(:after_inputs) do
{
gpm: 1.5,
dhw_cold_water_temperature: 80,
dhw_hot_water_temperature: 130,
showerhead_cost: 360
}
end
let!(:shared_inputs) do
{
# confirm that the num_occupants formula is used when input not provided
num_occupants: nil,
num_apartments: 10,
num_bedrooms: 10,
gas_cost_per_therm: 1,
water_cost_per_gallon: 0.00844
}
end
it { should_get_water_savings(43_840) }
it { should_get_gas_savings(128.4) }
it { should_get_cost_savings(498.4) }
it { should_get_cost_of_measure(360) }
it { should_get_years_to_payback(0.7) }
end
|
# gem install httparty
require 'httparty'
require 'uri'
require 'csv'
APPBOY_URL = 'https://api.appboy.com/users/track'
FILE_NAME = 'user_ids_to_export.csv'
VALID_ATTRIBUTE_PREFIX = 'looker_export.'
class AttributeExporter
def initialize
puts "1 for Elevate, 2 for Balance"
if gets.chomp == "1"
@is_elevate = true
else
@is_elevate = false
end
full_array = CSV.read(FILE_NAME, "r:ISO-8859-1")
@array_count = full_array.length
@array_of_ids = full_array.each_slice(50).to_a
header_row = @array_of_ids[0].shift
@attribute_name = header_row[1]
@user_id_column_name = header_row[0]
end
def send_if_confirmed
if is_valid_user_id_name
if is_valid_attribute_name
if is_confirmed
batch_send_attributes
else
puts "Attribute export cancelled."
end
else
puts "Second CSV column (attribute name) must start with 'looker_export.' Attribute name given: #{@attribute_name}"
end
else
puts "First CSV column (user ID) must be named 'user_id'"
end
end
private
def is_valid_user_id_name
@user_id_column_name == 'user_id'
end
def is_valid_attribute_name
@attribute_name.start_with?(VALID_ATTRIBUTE_PREFIX)
end
def is_confirmed
puts "Import #{@array_count} records to attribute name '#{@attribute_name}'? (y/n)"
return gets.chomp.downcase == 'y'
end
def batch_send_attributes
count = 0
@array_of_ids.each do |array_batch|
array_of_attributes = []
array_batch.each do |user_item|
count += 1
array_of_attributes << user_attributes_object(user_item)
end
attribute_payload = payload(array_of_attributes)
response = call_appboy(attribute_payload)
if response.code == 201
puts("#{count + 1} out of #{@array_count} users processed")
else
puts("Error:")
puts(response)
end
end
end
def call_appboy(attribute_payload)
HTTParty.post(APPBOY_URL, body: attribute_payload.to_json, headers: headers)
end
def payload(array_of_attributes)
if @is_elevate
app_group_id = ENV['APPBOY_APP_GROUP_ID_PRODUCTION']
else
app_group_id = ENV['APPBOY_APP_GROUP_ID_BALANCE_PRODUCTION']
end
{
"app_group_id" => app_group_id,
"attributes" => array_of_attributes,
"_update_existing_only" => true
}
end
def user_attributes_object(user_item)
user_id = user_item[0]
attribute_value = user_item[1]
{
"external_id" => user_id,
@attribute_name => attribute_value
}
end
def headers
{ 'Content-Type' => 'application/json' }
end
end
AttributeExporter.new.send_if_confirmed |
require 'vizier/visitors/base'
raise "This file currently not suitable for use"
#Should either become a subclass of VisitState or get absorbed where it's used
module Vizier
module Visitors
class ArgumentAddresser < Command
#TODO: this looks like parent's command_open...
def initialize(node, modules)
super(node)
@modules = modules
end
def completions(term)
return [] if invalid?
completions = @node.argument_list.find_all{|argument|
@modules.all?{|mod| argument.has_feature(mod)}
}.map{|argument| argument.name}
completions += @node.command_list.keys
completions += @node.mode_commands.keys
return completions.grep(/^#{term}.*/)
end
def get_argument(name)
@node.argument_list.find do |argument|
argument.name == name and @modules.all?{|mod| argument.has_feature(mod)}
end
end
end
end
end
|
require "rails_helper"
RSpec.describe "Incoming Call API", :as_twilio, type: :request do
describe "POST #create" do
context "with valid params" do
it "creates an incoming call" do
user = create(:user_with_number)
contact = create(:contact, user: user, phone_number: "+18285555000")
stub_const("ConnectCall", spy(call: Result.success(sid: "1234")))
post incoming_call_url, params: {
To: user.phone_number,
From: contact.phone_number,
CallSid: "1234",
}
call = IncomingCall.first
expect(call.user).to eq(user)
expect(call.contacts).to include(contact)
expect(response).to have_http_status(:created)
expect(response.body).to include("Enqueue")
end
it "recieves a call for a ring group" do
user = create(:user_with_number)
ring_group = create(:ring_group_with_number)
create(:ring_group_member, :available, user: user, ring_group: ring_group)
stub_const("ConnectCall", spy(call: Result.success(sid: "1234")))
post incoming_call_url, params: {
To: ring_group.phone_number,
From: "+18285555000",
CallSid: "1234",
}
call = RingGroupCall.first
expect(call.ring_group).to eq(ring_group)
expect(call.incoming_calls.count).to eq(1)
expect(response).to have_http_status(:created)
expect(response.body).to include("Enqueue")
end
end
end
end
|
class Comment < ActiveRecord::Base
searchkick callbacks: :async
belongs_to :user
belongs_to :post
default_scope { order('comments.updated_at DESC') }
end
|
require 'rails_helper'
RSpec.describe Admin::UsersController, type: :controller do
let(:valid_attributes) { attributes_for(:student) }
let(:invalid_attributes) {attributes_for(:invalid_user)}
describe 'Admin pages requires login' do
it "GET #index" do
get :index
expect(response).to redirect_to login_url
end
it "GET #new" do
get :new
expect(response).to redirect_to login_url
end
end
describe "GET #index & #new" do
before do
@admin = create(:admin)
login_user(@admin)
end
it "returns http success" do
get :index
expect(response).to have_http_status(:success)
end
it "returns http success" do
get :new
expect(response).to have_http_status(:success)
end
end
describe "POST #create with valid attributes" do
before do
@admin = create(:admin)
login_user(@admin)
end
it "redirects to admin_users_path" do
process :create, method: :post, params: {user: valid_attributes}
expect(response).to redirect_to(admin_users_path)
end
it "adds a new User record" do
expect{
process :create, method: :post, params: {user: valid_attributes}
}.to change(User,:count).by(1)
end
end
describe "POST #create with invalid attributes" do
before do
@admin = create(:admin)
login_user(@admin)
end
it "re-renders new template" do
process :create, method: :post, params: {user: invalid_attributes}
expect(response).to render_template :new
end
end
# describe "GET #destroy" do
# before do
# @admin = create(:admin)
# @student = create(:student)
# login_user(@admin)
# end
#
# it "redirects to admin_users_path" do
# expect{
# delete :destroy, :id => @admin, :user => {:password => @admin.password}
# }.to change(User, :count).by(-1)
# end
# end
end
|
require "integration_test_helper"
class MainstreamBrowsingTest < ActionDispatch::IntegrationTest
include RummagerHelpers
test "that we can handle all examples" do
# Shuffle the examples to ensure tests don't become order dependent
schemas = GovukSchemas::Example.find_all("mainstream_browse_page").shuffle
# Add all examples to the content store and rummager to allow pages to
# request their parents and links.
schemas.each do |content_item|
stub_content_store_has_item(content_item["base_path"], content_item)
rummager_has_documents_for_browse_page(
content_item["content_id"],
%w[
employee-tax-codes
get-paye-forms-p45-p60
pay-paye-penalty
pay-paye-tax
pay-psa
payroll-annual-reporting
],
page_size: RummagerSearch::PAGE_SIZE_TO_GET_EVERYTHING,
)
end
schemas.each do |content_item|
visit content_item["base_path"]
assert_equal 200, page.status_code
assert page.has_css?(".gem-c-breadcrumbs.gem-c-breadcrumbs--collapse-on-mobile"),
"Expected page at '#{content_item['base_path']}' to display breadcrumbs, but none found"
end
end
end
|
class RegController < ApplicationController
def index
end
def show
@reg = Reg.find(params[:id])
end
def new
@reg = Reg.new
end
def create
@reg = Reg.new(reg_params)
if @reg.save
redirect_to @reg
else
render 'new'
end
end
private
def reg_params
params.require(:rg).permit(:name,:contactno,:Emailid,:currentsemester,:Regid,:password)
end
end
|
json.array!(@ads) do |ad|
json.extract! ad, :id, :title, :body, :price, :created_at, :updated_at
json.user ad.user
json.categories ad.category
end
|
class Practice < ActiveRecord::Base
has_many :signups
has_many :players
end
|
Gem::Specification.new do |s|
s.name = 'zweb_spider'
s.version = '0.0.0'
s.date = '2015-04-01'
s.summary = "spider"
s.description = "a sample web spider just for fun"
s.authors = ["A kun"]
s.email = 'zhukun6150909@gmail.com'
s.files = ["lib/zweb_spider.rb"]
s.homepage = 'http://rubygems.org/gems/zweb_spider'
s.license = 'MIT'
end |
class Member < ApplicationRecord
devise :database_authenticatable, :recoverable, :rememberable, :trackable, :validatable, :encryptable, :omniauthable, :omniauth_providers => [:shibboleth], :encryptor => :restful_authentication_sha1, :authentication_keys => [:login]
has_many :event_roles
has_many :comments
has_many :timecard_entries
has_many :timecards, -> { distinct }, :through => :timecard_entries
has_many :super_tics, -> { order(day: :asc) }, dependent: :destroy
has_many :event_role_applications
accepts_nested_attributes_for :super_tics, :allow_destroy => true
attr_accessor :login
validates_presence_of :namefirst, :namelast, :payrate
validates_format_of :phone, :with => /\A\+?[0-9]*\Z/, :message => "must only use numbers"
before_validation do |m|
m.phone = m.phone.gsub(/[\.\- ]/, "") if m.phone
m.callsign.upcase! if m.callsign.respond_to? "upcase!"
unless is_at_least? :exec
m.super_tics.clear
end
end
extend Enumerize
enumerize :shirt_size, in: ["XS", "S", "M", "L", "XL", "2XL", "3XL"]
enumerize :role, in: [:suspended, :alumni, :general_member, :exec, :tracker_management, :head_of_tech], predicates: true
validates_presence_of :role
scope :can_be_supertic, -> { where(role: [:exec, :tracker_management, :head_of_tech]).order(namefirst: :asc, namelast: :asc) }
def active?
not suspended? and not alumni?
end
scope :active, -> { where.not(role: ["suspended", "alumni"]) }
scope :alphabetical, -> { order(namelast: :asc, namefirst: :asc) }
scope :with_role, ->(role) { where(role: role) }
def is_at_least?(pos)
Member.role.values.index(self.role) >= Member.role.values.index(pos.to_s)
end
Default_sort_key = "namelast"
def fullname
"#{namefirst} #{namelast}"
end
def display_name
if not namenick.blank?
namenick
else
fullname
end
end
def to_s
"#{fullname}"
end
def self.find_first_by_auth_conditions(warden_conditions)
conditions = warden_conditions.dup
if login = conditions.delete(:login)
where(conditions).where(["lower(email) = ? OR lower(email) = ?", login.downcase, login.downcase + "@andrew.cmu.edu"]).first
else
where(conditions).first
end
end
def active_for_authentication?
super and not suspended?
end
def ability
@ability ||= Ability.new(self)
end
def andrew?
email.end_with? "@andrew.cmu.edu"
end
end
|
# frozen_string_literal: true
class Bank
attr_accessor :money
def initialize(money = 0)
@money = money.to_i
end
def add_money(m)
self.money += m
end
def take_money(m)
self.money -= m if (money - m) >= 0
end
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.