text stringlengths 10 2.61M |
|---|
class I0020
attr_reader :title, :options, :name, :field_type, :node
def initialize
@title = "Section I: Active Diagnoses"
@name = "Indicate the resident's primary medical condition category. (Complete only if A0310b = 01 or 08) (I0020)"
@field_type = DROPDOWN
@node = "I0020"
@options = []
@options << FieldOption.new("^", "NA")
@options << FieldOption.new("01", "Stroke")
@options << FieldOption.new("02", "Non-Traumatic Brain Dysfunction")
@options << FieldOption.new("03", "Traumatic Brain Dysfunction")
@options << FieldOption.new("04", "Non-Traumatic Spinal Cord Dysfunction")
@options << FieldOption.new("05", "Traumatic Spinal Cord Dysfunction")
@options << FieldOption.new("06", "Progressive Neurological Conditions")
@options << FieldOption.new("07", "Other Neurological Conditions")
@options << FieldOption.new("08", "Amputation")
@options << FieldOption.new("09", "Hip and Knee Replacement")
@options << FieldOption.new("10", "Fractures and Other Multiple Trauma")
@options << FieldOption.new("11", "Other Orthopedic Conditions")
@options << FieldOption.new("12", "Debility, Cardiorespiratory Conditions")
@options << FieldOption.new("13", "Medically Complex Conditions")
end
def set_values_for_type(klass)
return "^"
end
end |
class QuestionsController < ApplicationController
def index
@questions = Question.all
end
def show
@question = Question.find(params[:id])
if !logged_in
flash.now[:warning] = "You cannot answer a question unless you are logged in!"
elsif !Answered.find_by(questionID: @question.id, teamID: current_user.team_id).nil?
flash.now[:warning] = "Your team has already answered this question!"
end
end
def submit
if !logged_in
redirect_to :back
else
@question = Question.find(params[:id])
if @question.answer.downcase == params[:answer].downcase
flash[:success] = "Question answered successfuly!"
Answered.create(teamID: current_user.team_id, questionID: @question.id)
# TODO(aaparella) : Check if there is an easier way to do this?
@t = Team.find(current_user.team_id)
@t.questions_answered += 1
@t.save
redirect_to questions_path
else
flash[:failure] = "Wrong answer"
redirect_to :back
end
end
end
end
|
# rubocop: disable Metrics/ParameterLists
def property_new \
id: nil,
human_ref: 2002,
occupiers: [Entity.new(title: 'Mr', initials: 'W G', name: 'Grace')],
address: address_new,
account: nil,
client: client_new,
agent: nil,
prepare: false
property = Property.new id: id, human_ref: human_ref
property.client = client if client
property.prepare_for_form if prepare
property.address = address
property.entities = occupiers if occupiers
property.account = account if account
property.build_agent authorized: false
property.agent = agent if agent
property
end
def property_create \
id: nil,
human_ref: 2002,
occupiers: [Entity.new(title: 'Mr', initials: 'W G', name: 'Grace')],
address: address_new,
account: nil,
client: client_create,
agent: nil,
prepare: false
property = property_new id: id,
human_ref: human_ref,
occupiers: occupiers,
address: address,
account: account,
client: client,
agent: agent,
prepare: prepare
property.save!
property
end
|
# == Schema Information
#
# Table name: all_jokes
#
# id :bigint(8) not null, primary key
# joke :string
# joke_type :integer
# sequence :integer
# uuid :integer
# created_at :datetime not null
# updated_at :datetime not null
#
require 'rails_helper'
RSpec.describe AllJoke, type: :model do
describe "associations" do
it { is_expected.to have_many(:used_jokes).dependent(:destroy) }
end
describe "validations" do
it { is_expected.to validate_presence_of(:joke) }
it { is_expected.to validate_presence_of(:joke_type) }
it { is_expected.to validate_presence_of(:sequence) }
it { is_expected.to validate_presence_of(:uuid) }
it { is_expected.to validate_uniqueness_of(:uuid) }
it {
is_expected.to(
validate_numericality_of(:sequence)
)
}
it {
is_expected.to(
validate_numericality_of(:uuid)
)
}
it {
should validate_uniqueness_of(:sequence).scoped_to(:joke_type)
}
end
end
|
class AccountCodesController < ApplicationController
def destroy
@project = current_user.owned_projects.find(params[:project_id])
ids = SuretyMember.where(surety_id: @project.surety_ids).pluck(:account_code_id)
ac = AccountCode.where(id: ids).find(params[:id])
ac.destroy
redirect_to @project
end
end
|
class AddColumnRucAndAddressToWorkPartners < ActiveRecord::Migration
def change
add_column :work_partners, :ruc, :string
add_column :work_partners, :address, :text
end
end
|
module Wallet
class Credit < ApplicationRecord
belongs_to :account, class_name: "Wallet::Account", foreign_key: "wallet_account_id"
end
end
|
class User::Customer < User
has_many :tickets, foreign_key: :customer_id
has_many :messages, foreign_key: :customer_id
end
|
class User < ApplicationRecord
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
enum role: { user: 0, admin: 1, provider: 2, manager: 3 }
belongs_to :payment_information, optional: true
belongs_to :juristic_document, optional: true
belongs_to :user_info, optional: true
has_many :shipment_informations
has_many :orders
has_many :favorites
has_many :tickets
has_attached_file :eugrl
validates_attachment :eugrl, :content_type => {:content_type => %w(image/jpeg image/jpg image/png application/pdf application/msword application/vnd.openxmlformats-officedocument.wordprocessingml.document)}
has_attached_file :traders_cart
validates_attachment :traders_cart, :content_type => {:content_type => %w(image/jpeg image/jpg image/png application/pdf application/msword application/vnd.openxmlformats-officedocument.wordprocessingml.document)}
def documents(presence_need = true)
documents = {}
documents['eugrl'] = {
title: 'Выписка из ЕЮГРЛ',
document: self.eugrl,
} if self.eugrl.exists? || !presence_need
documents['traders_cart'] = {
title: 'Карта партнера',
document: self.traders_cart,
} if self.traders_cart.exists? || !presence_need
documents
end
end
|
# Class to create an inventory record
# We're using class 6 to create getters and setters
# getters just get the data from the class
# We write getters and setters for the size array because we don't want to expose to the outside world that we are using an array
# remeber that getters return what is being asked for, and writers allow you to change something.
class Item
# The shortcut for getters, setters, and instance variables is attr_accessor :NAME, for just a getter write attr_reader :VARNAME, for just a setter attr_writer :VARNAME
# :VARNAME in the above is essentially a constant string
attr_accessor :description, :price
# Setting instance variables
# The ID should be a random 3 digit number
def initialize( description, price )
@id = rand(100..999)
@description = description
@price = price
@size = []
end
# THE FOLLOWING CODE FOR DESCRIPTION AND PRICE BECOMES REDUNDANT WITH THE ABOVE attr_accessor
# Getter for description
def description
return @description
end
# Setter for description
def description=( description )
@description = description
end
def price
return @price
end
def price=( price )
@price = price
end
def id
return @id
end
# adding and removing sizes
def add_size( size )
@size << size
end
def remove_size( size )
@size.delete( size )
end
def sizes
return @size
end
# Overwriting the string method to apply to this Class/object
def to_s
return "#{@id}\t #{@description}\t #{@price}\t Sizes: #{@size.join(", ")}"
end
end
shirt = Item.new( "shirt", 19.99 )
shirt.add_size( "Large" )
shirt.add_size( "Small" )
puts shirt
#shirt.remove_size( "Small" )
puts shirt
puts shirt.description
puts shirt.price
# Change values
shirt.description = "HI shirt"
shirt.price = 75.00
# Output the values that we just changed
puts shirt.description
puts shirt.price
shirt.sizes.each do | size |
puts size + " HELLO "
end |
class RPagesController < ApplicationController
before_action :set_r_page, only: [:show, :edit, :update, :destroy]
# GET /r_pages
# GET /r_pages.json
def index
@r_pages = RPage.all
end
# GET /r_pages/1
# GET /r_pages/1.json
def show
end
# GET /r_pages/new
def new
@r_page = RPage.new
end
# GET /r_pages/1/edit
def edit
end
# POST /r_pages
# POST /r_pages.json
def create
@r_page = RPage.new(r_page_params)
respond_to do |format|
if @r_page.save
format.html { redirect_to @r_page, notice: 'R page was successfully created.' }
format.json { render action: 'show', status: :created, location: @r_page }
else
format.html { render action: 'new' }
format.json { render json: @r_page.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /r_pages/1
# PATCH/PUT /r_pages/1.json
def update
respond_to do |format|
if @r_page.update(r_page_params)
format.html { redirect_to @r_page, notice: 'R page was successfully updated.' }
format.json { head :no_content }
else
format.html { render action: 'edit' }
format.json { render json: @r_page.errors, status: :unprocessable_entity }
end
end
end
# DELETE /r_pages/1
# DELETE /r_pages/1.json
def destroy
@r_page.destroy
respond_to do |format|
format.html { redirect_to r_pages_url }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_r_page
@r_page = RPage.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def r_page_params
params.require(:r_page).permit(:r_language_id, :name, :template, :properties)
end
end
|
class Player
attr_accessor :cards, :amount
attr_reader :name
def initialize(name, amount)
@name = name
@amount = amount
@cards = []
end
end
|
Vagrant.configure("2") do |config|
# Run `vagrant rsync-auto` to sync the shared directory automatically
config.vm.synced_folder "..", "/vagrant", type: "rsync"
config.vm.define "main" do |main|
main.vm.box = "ubuntu/xenial64"
main.vm.network "private_network", ip: "10.10.10.10"
main.vm.hostname = "main"
main.vm.provider "virtualbox" do |vb|
vb.name = "main"
end
main.vm.provision :salt do |salt|
salt.masterless = true
salt.minion_config = "minion"
salt.run_highstate = true
salt.colorize = false
end
end
end
|
class Follow < ApplicationRecord
# Direct associations
belongs_to :stock,
:counter_cache => true
belongs_to :user
# Indirect associations
# Validations
validates :stock_id, :uniqueness => { :scope => [:user_id], :message => "already liked" }
validates :stock_id, :presence => true
validates :user_id, :presence => true
end
|
require_relative "lib/lorem_ipsum_nearby/version"
Gem::Specification.new do |spec|
spec.name = "lorem_ipsum_nearby"
spec.version = LoremIpsumNearby::VERSION
spec.authors = ["A T M Hassan Uzzaman"]
spec.email = ["sajib.hassan@gmail.com"]
spec.summary = "This is a gem for a Tech challenge"
spec.description = "We have some customer records in a text file (data/customers.json) -- one customer data per line, JSON-encoded. We want to invite any customer within 100km of our X office for some food and drinks.
Write a program that will read the full list of customers and output the names and user ids of matching customers (within 100km), sorted by User ID (ascending).
- You can use the first formula from this Wikipedia article to calculate distance. Don't forget, you'll need to convert degrees to radians.
- The GPS coordinates for our X office are 52.508283, 13.329657
- You can find the Customer list here - https://gist.github.com/xxx/aaaaaaa"
spec.homepage = "https://github.com/sajib-hassan/lorem-ipsum-nearby-ruby.git"
spec.license = "MIT"
spec.required_ruby_version = Gem::Requirement.new(">= 2.3.0")
spec.metadata["allowed_push_host"] = "https://github.com/sajib-hassan/lorem-ipsum-nearby-ruby.git"
spec.metadata["homepage_uri"] = spec.homepage
spec.metadata["source_code_uri"] = "https://github.com/sajib-hassan/lorem-ipsum-nearby-ruby.git"
spec.metadata["changelog_uri"] = "https://github.com/sajib-hassan/lorem-ipsum-nearby-ruby.git"
# Specify which files should be added to the gem when it is released.
# The `git ls-files -z` loads the files in the RubyGem that have been added into git.
spec.files = Dir.chdir(File.expand_path("..", __FILE__)) do
`git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) }
end
spec.bindir = "exe"
spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
spec.require_paths = ["lib"]
end
|
module MTMD
module FamilyCookBook
module Search
class RecipeByIngredient < ::MTMD::FamilyCookBook::Search::Recipe
def query(phrase)
MTMD::FamilyCookBook::Recipe.
where(
:id => MTMD::FamilyCookBook::Ingredient.
association_join(:ingredient_quantities).
where(Sequel.ilike(:ingredients__title, "%#{phrase}%")).
select_map(:recipe_id)
).
order(:title).
all
end
end
end
end
end
|
class AddAndRemoveFieldsToSite < ActiveRecord::Migration
def change
add_column :sites, :status, :string
add_column :sites, :contact_name, :string
add_column :sites, :contact_phone, :string
add_column :sites, :contact_phone_ext, :string
add_column :sites, :contact_email, :string
remove_column :sites, :street_address
remove_column :sites, :street_address2
change_column_null :sites, :trial_id, false
end
end
|
require 'hotel_beds/parser'
require 'hotel_beds/parser/cancellation_policy'
require 'hotel_beds/parser/price'
require 'hotel_beds/parser/customer'
require 'hotel_beds/parser/tax'
module HotelBeds
module Parser
class AvailableRoom
include HotelBeds::Parser
# attributes
attribute :id, selector: 'HotelRoom', attr: 'SHRUI'
attribute :room_count, selector: 'HotelOccupancy RoomCount'
attribute :adult_count, selector: 'HotelOccupancy AdultCount'
attribute :child_count, selector: 'HotelOccupancy ChildCount'
attribute :number_available, selector: 'HotelRoom', attr: 'availCount'
attribute :description, selector: 'HotelRoom RoomType'
attribute :board, selector: 'HotelRoom Board'
attribute :board_code, selector: 'HotelRoom Board', attr: 'code'
attribute :room_type_code, selector: 'HotelRoom RoomType', attr: 'code'
attribute :room_type_characteristic,
selector: 'HotelRoom RoomType', attr: 'characteristic'
attribute :price_amount, selector: 'HotelRoom > Price > Amount'
attribute :net_price, selector: 'HotelRoom > Price > NetPrice'
attribute :selling_price, selector: 'HotelRoom > Price > SellingPrice'
attribute :is_selling_price_mandatory, selector: 'HotelRoom > Price > SellingPrice', attr: 'mandatory'
attribute :taxes,
selector: 'HotelRoom > TaxList > Tax', multiple: true,
parser: HotelBeds::Parser::Tax
attribute :cancellation_policies,
selector: 'HotelRoom > CancellationPolicies > CancellationPolicy', multiple: true,
parser: HotelBeds::Parser::CancellationPolicy
attribute :basket_cancellation_policy,
selector: 'HotelRoom > CancellationPolicy > Price', multiple: true,
parser: HotelBeds::Parser::CancellationPolicy
attribute :rates,
selector: 'Price PriceList Price', multiple: true,
parser: HotelBeds::Parser::Price
attribute :customers,
selector: 'HotelOccupancy GuestList Customer', multiple: true,
parser: HotelBeds::Parser::Customer
end
end
end
|
require 'money'
require_relative '../../../lib/customers/customer'
require_relative '../../../lib/customers/card'
require_relative '../../../lib/supervisor'
require_relative '../../../lib/payments/transactions/transaction'
require_relative '../../../lib/event_handler'
require_relative '../../../lib/payments/transactions/supervisor'
describe Charger::Customer do
let(:supervisor) { Charger::Supervisor.new(input: 'input.txt') }
let(:transaction_supervisor) { Charger::Transactions::Supervisor.new(supervisor: supervisor) }
subject { Charger::Customer.new("Fred") }
it "adds new cards" do
expect(subject.cards).to be_empty
subject.new_card("4111111111111111", 10_000)
expect(subject.cards).not_to be_empty
end
it "provides balance for card" do
subject.new_card("4111111111111111", 10_000)
expect(subject.balance.to_f).to eq(0)
proc = -> {
Charger::EventHandler.new.process(event: "Add #{subject.cards.last.number} $10,000", supervisor: supervisor)
Charger::Transactions::Transaction.process(data: [:credit, subject.cards.last, 50])
}
expect { proc.call }.to change { subject.balance }.by(Money.new(-50, :usd))
end
end
|
class FBCredentialsProvider < Facebook::Messenger::Configuration::Providers::Base
def valid_verify_token?(verify_token)
verify_token == ENV['FB_MESSENGER_VERIFY_TOKEN']
end
def app_secret_for(*)
ENV['FB_MESSENGER_APP_SECRET']
end
def access_token_for(*)
ENV['FB_MESSENGER_ACCESS_TOKEN']
end
end
Facebook::Messenger.configure do |config|
config.provider = FBCredentialsProvider.new
end
unless Rails.env.production?
bot_files = Dir[Rails.root.join('app', 'my_bot', '**', '*.rb')]
bot_reloader = ActiveSupport::FileUpdateChecker.new(bot_files) do
bot_files.each { |file| require_dependency file }
end
ActiveSupport::Reloader.to_prepare do
bot_reloader.execute_if_updated
end
bot_files.each { |file| require_dependency file }
end
|
# frozen_string_literal: true
module Validations
def self.included(base)
base.extend ClassMethods
base.send :include, InstanceMethods
end
# rubocop:disable Metrics/MethodLength
# rubocop:disable Metrics/LineLength
# rubocop:disable Metrics/AbcSize
# rubocop:disable Metrics/CyclomaticComplexity
module ClassMethods
attr_reader :validations
def validate(attr_name, validation_type, *args)
attribute_name = attr_name.to_sym
validation_type_name = validation_type.to_s.to_sym
method_name = "#{validation_type_name}_of_#{attribute_name}"
option = args[0]
@validations ||= []
case validation_type_name
when :presence
define_method(method_name) do
if instance_variable_get("@#{attribute_name}".to_sym).nil? || instance_variable_get("@#{attribute_name}".to_sym) == ""
raise "No argument was provided."
end
end
@validations << method_name
when :type
define_method(method_name) do
unless instance_variable_get("@#{attribute_name}".to_sym).class.to_s == option.to_s
raise "Wrong type."
end
end
@validations << method_name
when :format
define_method(method_name) do
unless instance_variable_get("@#{attribute_name}".to_sym).match? option
raise "Wrong format of @#{attribute_name}"
end
end
@validations << method_name
end
end
end
# rubocop:enable Metrics/CyclomaticComplexity
# rubocop:enable Metrics/AbcSize
# rubocop:enable Metrics/LineLength
# rubocop:enable Metrics/MethodLength
module InstanceMethods
# rubocop:disable Security/Eval
def validate!
self.class.validations.each { |validation| eval(validation) }
true
end
# rubocop:enable Security/Eval
def valid?
validate!
rescue StandardError
false
end
end
end
|
# frozen_string_literal: true
# rubocop:todo all
# Copyright (C) 2014-2020 MongoDB Inc.
#
# 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 Mongo
module Index
# A class representing a view of indexes.
#
# @since 2.0.0
class View
extend Forwardable
include Enumerable
include Retryable
# @return [ Collection ] collection The indexes collection.
attr_reader :collection
# @return [ Integer ] batch_size The size of the batch of results
# when sending the listIndexes command.
attr_reader :batch_size
def_delegators :@collection, :cluster, :database, :read_preference, :write_concern, :client
def_delegators :cluster, :next_primary
# The index key field.
#
# @since 2.0.0
KEY = 'key'.freeze
# The index name field.
#
# @since 2.0.0
NAME = 'name'.freeze
# The mappings of Ruby index options to server options.
#
# @since 2.0.0
OPTIONS = {
:background => :background,
:bits => :bits,
:bucket_size => :bucketSize,
:default_language => :default_language,
:expire_after => :expireAfterSeconds,
:expire_after_seconds => :expireAfterSeconds,
:key => :key,
:language_override => :language_override,
:max => :max,
:min => :min,
:name => :name,
:partial_filter_expression => :partialFilterExpression,
:sparse => :sparse,
:sphere_version => :'2dsphereIndexVersion',
:storage_engine => :storageEngine,
:text_version => :textIndexVersion,
:unique => :unique,
:version => :v,
:weights => :weights,
:collation => :collation,
:comment => :comment,
:wildcard_projection => :wildcardProjection,
}.freeze
# Drop an index by its name.
#
# @example Drop an index by its name.
# view.drop_one('name_1')
#
# @param [ String ] name The name of the index.
# @param [ Hash ] options Options for this operation.
#
# @option options [ Object ] :comment A user-provided
# comment to attach to this command.
#
# @return [ Result ] The response.
#
# @since 2.0.0
def drop_one(name, options = {})
raise Error::MultiIndexDrop.new if name == Index::ALL
drop_by_name(name, comment: options[:comment])
end
# Drop all indexes on the collection.
#
# @example Drop all indexes on the collection.
# view.drop_all
#
# @param [ Hash ] options Options for this operation.
#
# @option options [ Object ] :comment A user-provided
# comment to attach to this command.
#
# @return [ Result ] The response.
#
# @since 2.0.0
def drop_all(options = {})
drop_by_name(Index::ALL, comment: options[:comment])
end
# Creates an index on the collection.
#
# @example Create a unique index on the collection.
# view.create_one({ name: 1 }, { unique: true })
#
# @param [ Hash ] keys A hash of field name/direction pairs.
# @param [ Hash ] options Options for this index.
#
# @option options [ true, false ] :unique (false) If true, this index will enforce
# a uniqueness constraint on that field.
# @option options [ true, false ] :background (false) If true, the index will be built
# in the background (only available for server versions >= 1.3.2 )
# @option options [ true, false ] :drop_dups (false) If creating a unique index on
# this collection, this option will keep the first document the database indexes
# and drop all subsequent documents with duplicate values on this field.
# @option options [ Integer ] :bucket_size (nil) For use with geoHaystack indexes.
# Number of documents to group together within a certain proximity to a given
# longitude and latitude.
# @option options [ Integer ] :max (nil) Specify the max latitude and longitude for
# a geo index.
# @option options [ Integer ] :min (nil) Specify the min latitude and longitude for
# a geo index.
# @option options [ Hash ] :partial_filter_expression Specify a filter for a partial
# index.
# @option options [ Boolean ] :hidden When :hidden is true, this index will
# exist on the collection but not be used by the query planner when
# executing operations.
# @option options [ String | Integer ] :commit_quorum Specify how many
# data-bearing members of a replica set, including the primary, must
# complete the index builds successfully before the primary marks
# the indexes as ready. Potential values are:
# - an integer from 0 to the number of members of the replica set
# - "majority" indicating that a majority of data bearing nodes must vote
# - "votingMembers" which means that all voting data bearing nodes must vote
# @option options [ Session ] :session The session to use for the operation.
# @option options [ Object ] :comment A user-provided
# comment to attach to this command.
#
# @note Note that the options listed may be subset of those available.
# See the MongoDB documentation for a full list of supported options by server version.
#
# @return [ Result ] The response.
#
# @since 2.0.0
def create_one(keys, options = {})
options = options.dup
create_options = {}
if session = @options[:session]
create_options[:session] = session
end
%i(commit_quorum session comment).each do |key|
if value = options.delete(key)
create_options[key] = value
end
end
create_many({ key: keys }.merge(options), create_options)
end
# Creates multiple indexes on the collection.
#
# @example Create multiple indexes.
# view.create_many([
# { key: { name: 1 }, unique: true },
# { key: { age: -1 }, background: true }
# ])
#
# @example Create multiple indexes with options.
# view.create_many(
# { key: { name: 1 }, unique: true },
# { key: { age: -1 }, background: true },
# { commit_quorum: 'majority' }
# )
#
# @note On MongoDB 3.0.0 and higher, the indexes will be created in
# parallel on the server.
#
# @param [ Array<Hash> ] models The index specifications. Each model MUST
# include a :key option, except for the last item in the Array, which
# may be a Hash specifying options relevant to the createIndexes operation.
# The following options are accepted:
# - commit_quorum: Specify how many data-bearing members of a replica set,
# including the primary, must complete the index builds successfully
# before the primary marks the indexes as ready. Potential values are:
# - an integer from 0 to the number of members of the replica set
# - "majority" indicating that a majority of data bearing nodes must vote
# - "votingMembers" which means that all voting data bearing nodes must vote
# - session: The session to use.
# - comment: A user-provided comment to attach to this command.
#
# @return [ Result ] The result of the command.
#
# @since 2.0.0
def create_many(*models)
models = models.flatten
options = {}
if models && !models.last.key?(:key)
options = models.pop
end
client.send(:with_session, @options.merge(options)) do |session|
server = next_primary(nil, session)
indexes = normalize_models(models, server)
indexes.each do |index|
if index[:bucketSize] || index['bucketSize']
client.log_warn("Haystack indexes (bucketSize index option) are deprecated as of MongoDB 4.4")
end
end
spec = {
indexes: indexes,
db_name: database.name,
coll_name: collection.name,
session: session,
commit_quorum: options[:commit_quorum],
write_concern: write_concern,
comment: options[:comment],
}
Operation::CreateIndex.new(spec).execute(server, context: Operation::Context.new(client: client, session: session))
end
end
# Convenience method for getting index information by a specific name or
# spec.
#
# @example Get index information by name.
# view.get('name_1')
#
# @example Get index information by the keys.
# view.get(name: 1)
#
# @param [ Hash, String ] keys_or_name The index name or spec.
#
# @return [ Hash ] The index information.
#
# @since 2.0.0
def get(keys_or_name)
find do |index|
(index[NAME] == keys_or_name) || (index[KEY] == normalize_keys(keys_or_name))
end
end
# Iterate over all indexes for the collection.
#
# @example Get all the indexes.
# view.each do |index|
# ...
# end
#
# @since 2.0.0
def each(&block)
session = client.send(:get_session, @options)
cursor = read_with_retry_cursor(session, ServerSelector.primary, self) do |server|
send_initial_query(server, session)
end
if block_given?
cursor.each do |doc|
yield doc
end
else
cursor.to_enum
end
end
# Create the new index view.
#
# @example Create the new index view.
# View::Index.new(collection)
#
# @param [ Collection ] collection The collection.
# @param [ Hash ] options Options for getting a list of indexes.
# Only relevant for when the listIndexes command is used with server
# versions >=2.8.
#
# @option options [ Integer ] :batch_size The batch size for results
# returned from the listIndexes command.
#
# @since 2.0.0
def initialize(collection, options = {})
@collection = collection
@batch_size = options[:batch_size]
@options = options
end
private
def drop_by_name(name, comment: nil)
client.send(:with_session, @options) do |session|
spec = {
db_name: database.name,
coll_name: collection.name,
index_name: name,
session: session,
write_concern: write_concern,
}
spec[:comment] = comment unless comment.nil?
server = next_primary(nil, session)
Operation::DropIndex.new(spec).execute(server, context: Operation::Context.new(client: client, session: session))
end
end
def index_name(spec)
spec.to_a.join('_')
end
def indexes_spec(session)
{ selector: {
listIndexes: collection.name,
cursor: batch_size ? { batchSize: batch_size } : {} },
coll_name: collection.name,
db_name: database.name,
session: session
}
end
def initial_query_op(session)
Operation::Indexes.new(indexes_spec(session))
end
def limit; -1; end
def normalize_keys(spec)
return false if spec.is_a?(String)
Options::Mapper.transform_keys_to_strings(spec)
end
def normalize_models(models, server)
models.map do |model|
# Transform options first which gives us a mutable hash
Options::Mapper.transform(model, OPTIONS).tap do |model|
model[:name] ||= index_name(model.fetch(:key))
end
end
end
def send_initial_query(server, session)
initial_query_op(session).execute(server, context: Operation::Context.new(client: client, session: session))
end
end
end
end
|
require 'poke'
def game(pokes)
possible_board = pokes.combination(5).to_a
possible_board.map {|board| compute_result(board)}.min
end
def compute_result(pokes)
duplicate_cards_sort = duplicate_cards(pokes).values.sort
flush = flush?(pokes)
straight = straight?(pokes)
has_max_card = has_max_card?(pokes)
return 0 if has_max_card && straight && flush
return 1 if straight && flush
return 2 if duplicate_cards_sort == [1, 4]
return 3 if duplicate_cards_sort == [2, 3]
return 4 if flush && duplicate_cards_sort == [1, 1, 1, 1, 1]
return 5 if straight
return 6 if duplicate_cards_sort == [1, 1, 3]
return 7 if duplicate_cards_sort == [1, 2, 2]
return 8 if duplicate_cards_sort == [1, 1, 1, 2]
return 9 if duplicate_cards_sort == [1, 1, 1, 1, 1]
end
def duplicate_cards(pokes)
dup = {}
pokes.each do |poke|
next if dup.has_key?(poke.num)
dup[poke.num] = pokes.map(&:num).count(poke.num)
end
dup
end
def flush?(pokes)
pokes.map(&:color).uniq.size == 1
end
def has_max_card?(pokes)
pokes.any? {|poke| poke.num == "A"}
end
def straight?(pokes)
int_nums = num_to_int(pokes)
int_nums.reduce(:+) == int_nums.min * 5 + 10
end
def num_to_int(pokes)
int_array = []
pokes.each do |poke|
case poke.num
when "A"
int_array << 14
when "J"
int_array << 11
when "Q"
int_array << 12
when "K"
int_array << 13
else
int_array << poke.num.to_i
end
end
int_array
end
|
class Favourite < ActiveRecord::Base
# Associations
belongs_to :user
belongs_to :work
# Checks if user has already favourited the work once.
validate :user_has_not_favourited_work
# Check if the user has already favourited the work before and throw an error if so
def user_has_not_favourited_work
errors.add('You cannot favourite a work twice.') unless Favourite.find_by(user_id: self.user_id, work_id: self.work_id).nil?
end
end
|
class Sport < ApplicationRecord
has_attachment :photo
has_many :events, inverse_of: :sport
has_many :favorite_sports
has_many :users, through: :favorite_sports
validates :name, presence: true
validates :name, uniqueness: true
end
|
class Comment < ApplicationRecord
belongs_to :post
validates :nickname, presence: true
validates :body, presence: true
end
|
# Require dependencies.
# sinatra - lightweight web framework
# json - for JSON marshalling.
require 'sinatra'
require 'json'
require 'securerandom'
# Setup const for json content type.
JSON_CONTENT_TYPE = 'application/json'
# Methods needed for / endpoint.
# This tells the API server what endpoints are available
# to the SG.
REGISTERED_METHODS = {
'/providers' => {
'GET' => [{}],
'POST' => {'params' => {'url' => 'redis://example.redis.com:6379'}}
},
'/providers/:id' => {
'GET' => {'params' => {'url' => 'redis://example.redis.com:6379'}},
'DELETE' => {}
},
'/services' => {
'GET' => [{}],
'POST' => {}
},
'/services/:id' => {
'GET' => {'params' => {'db' => '0'}},
'DELETE' => {}
},
'/bindings' => {
'GET' => [{}],
'POST' => {}
},
'/bindings/:id' => {
'GET' => {},
'DELETE' => {}
},
}
# Place the API server checks for methods that are supported.
get '/' do
content_type JSON_CONTENT_TYPE
REGISTERED_METHODS.to_json
end
# No persistent data store, just build up some arrays and class vars.
@@providers = []
@@services = []
@@bindings = []
# Create a provider
post '/providers' do
content_type JSON_CONTENT_TYPE
data = JSON.parse(request.body.read)
uri = URI(data['params']['url'])
hostname = uri.hostname
provider = {}
provider['id'] = SecureRandom.uuid
provider['name'] = "redis-server-#{hostname}"
provider['description'] = "Redis Server at #{hostname}"
provider['params'] = data['params']
provider['type'] = 'redis'
@@providers << provider
provider.to_json
end
# List providers.
get '/providers/?' do
content_type JSON_CONTENT_TYPE
@@providers.to_json
end
# Get a provider.
get '/providers/:id' do
content_type JSON_CONTENT_TYPE
provider = @@providers.detect { |p| p['id'] == params['id'] }
halt 404 unless provider
provider.to_json
end
# Remove a provider.
delete '/providers/:id' do
content_type JSON_CONTENT_TYPE
provider = @@providers.detect {|provider| provider['id'] == params['id'] }
halt 404 unless provider
@@providers.delete_if {|p| p['id'] == provider['id'] }
provider.to_json
end
# Track dbs we have services for.
@@redis_dbs = []
(0...100).each do |db|
@@redis_dbs << {:used => false, :db => db }
end
# Create a service for a single redis db 0 - 12.
post '/services' do
content_type JSON_CONTENT_TYPE
data = JSON.parse(request.body.read)
# Return an existing service if the db id requested is a duplicate.
if data['params'] && data['params']['db']
if service = @@services.detect {|s| s['params']['db'] && (s['params']['db'].to_i == data['params']['db'].to_i)}
return service.to_json
end
end
provider = @@providers.detect {|p| p['id'] == data['provider_id']}
halt 404 unless provider
uri = URI(provider['params']['url'])
hostname = uri.hostname
# Check to see if db requested is in use, or find a db that is unused if none was provided.
db = nil
if db_id = data['params'] && data['params']['db']
db = @@redis_dbs.detect { |rdb| rdb[:db].to_i == db_id.to_i }
else
db = @@redis_dbs.detect { |rdb| rdb[:used] == false }
end
halt 404 unless db # return 404 in case there is no redis db available
# Build new service object.
service = { }
service['id'] = SecureRandom.uuid
service['name'] = "redis-db-#{db[:db]}"
service['description'] = "Redis DB at #{hostname}/#{db[:db]}"
service['provider_id'] = provider['id']
service['params'] = { 'db' => db[:db] }
db[:used] = true
@@services << service
service.to_json
end
# Get a list of services.
get '/services/?' do
content_type JSON_CONTENT_TYPE
@@services.to_json
end
# Get a specific service.
get '/services/:id' do
content_type JSON_CONTENT_TYPE
service = @@services.detect {|service| service['id'].to_s == params['id'] }
halt 404 unless service
service.to_json
end
# Remove a service.
delete '/services/:id' do
content_type JSON_CONTENT_TYPE
service = @@services.detect {|service| service['id'] == params['id'] }
halt 404 unless service
@@services.delete_if {|s| s['id'] == service['id'] }
db = @@redis_dbs.detect {|rdb| rdb[:db].to_i == service['params']['db'].to_i }
db[:used] = false
service.to_json
end
# Create a binding.
post '/bindings' do
content_type JSON_CONTENT_TYPE
data = JSON.parse(request.body.read)
service = @@services.detect {|service| service['id'] == data['service_id'] }
halt 404 unless service
provider = @@providers.detect{|provider| provider['id'] == service['provider_id']}
halt 404 unless provider
binding = {
'id' => SecureRandom.uuid,
'name' => "redis-binding-to-#{service['name']}",
'service_id' => service['id'],
'url' => "#{provider['params']['url']}/#{service['params']['db']}",
'protocol' => { 'scheme' => 'redis'}
}
@@bindings << binding
binding.to_json
end
# Get list of bindings.
get '/bindings/?' do
content_type JSON_CONTENT_TYPE
@@bindings.to_json
end
# Get one binding.
get '/bindings/:id' do
content_type JSON_CONTENT_TYPE
binding = @@bindings.detect {|b| b['id'] == params['id'] }
halt 404 unless binding
binding.to_json
end
# Delete a binding.
delete '/bindings/:id' do
content_type JSON_CONTENT_TYPE
binding = @@bindings.detect {|b| b['id'] == params['id'] }
halt 404 unless binding
@@bindings.delete_if {|b| b['id'] == binding['id'] }
binding.to_json
end |
require "fileutils"
if ENV['random']
random_dir = File.expand_path ENV['random']
unless File.directory?(random_dir)
$stderr.puts "Unable to find source directory #{random_dir}"
exit 1
end
candidates = Dir[random_dir + "/**/*.wav"].shuffle
unless candidates.size > 1
$stderr.puts "Source directory #{random_dir} must have at least 2 audio files"
exit 1
end
file1 = candidates[0]
file2 = candidates[1]
outfilename = ARGV[0]
unless outfilename
$stderr.puts "Please pass in an output file name"
exit 1
end
elsif ARGV.size < 3
$stderr.puts <<-END
Usage: ruby wavetables.rb file1.wav file2.wav outfilename
END
exit 1
else
missing_files = ARGV.first(2).select {|f| !File.file?(f) }
unless missing_files.empty?
$stderr.puts <<-END
Missing files: #{missing_files.join(", ")}
END
exit 1
end
file1 = ARGV[0]
file2 = ARGV[1]
outfilename = ARGV[2]
end
gen_dir = "_gen"
FileUtils.mkdir(gen_dir) unless File.directory?(gen_dir)
interpolations_dir = "#{gen_dir}/interpolations"
FileUtils.rm_rf interpolations_dir
FileUtils.mkdir_p interpolations_dir
if ENV['wt_dir']
wt_dir = File.expand_path(ENV['wt_dir'])
unless File.directory?(wt_dir)
$stderr.puts "Wavetable dir #{wt_dir} is missing"
exit
end
else
wt_dir = "#{gen_dir}/wavetables"
FileUtils.mkdir(wt_dir) unless File.directory?(wt_dir)
end
`submix inbetween 1 "#{file1}" "#{file2}" #{interpolations_dir}/output 128`
if `sndinfo props #{interpolations_dir}/output001.wav` =~ /^samples\:.* (\d+)$/
size = $1
outfile = "#{wt_dir}/#{outfilename}_#{size}.wav"
count = 0
until !File.file?(outfile)
count += 1
outfile = "#{wt_dir}/#{outfilename}-#{count}_#{size}.wav"
end
`sfedit join #{interpolations_dir}/output*.wav #{outfile} -w0`
puts "File written to #{outfile}"
end
|
require 'spec_helper'
require 'yt/errors/forbidden'
describe Yt::Errors::Forbidden do
let(:msg) { %r{^A request to YouTube API was considered forbidden by the server} }
describe '#exception' do
it { expect{raise Yt::Errors::Forbidden}.to raise_error msg }
end
end |
# Course controller
class CoursesController < ApplicationController
before_action :find_course, except: %w[index new create]
before_action :find_instructors, only: %w[new edit]
def index
@courses = policy_scope(Course)
authorize @courses
end
def new
@course = Course.new
authorize @course
end
def edit
authorize @course
end
def update
authorize @course
@course.assign_attributes(course_params)
if @course.save
redirect_to course_path(@course), flash: { success: 'Course updated' }
else
render :edit
end
end
def create
@course = Course.new(course_params)
authorize @course
if @course.save
redirect_to course_path(@course), flash: { success: 'Course created' }
else
find_instructors
render :new
end
end
def show
authorize @course
end
def destroy
if @course.destroy
redirect_to courses_path
else
redirect_to course_path(@course)
end
end
private
def find_course
@course = Course.friendly.find(params[:id])
end
def find_instructors
@instructors = User.instructors
end
def course_params
params.require(:course).permit(:name, :instructor_id, :start_time, :end_time, :description)
end
end
|
class OrganizationsController < ApplicationController
def show
@organizations = Organization.find(params[:id])
end
end
|
class Item < ActiveRecord::Base
belongs_to :sale
belongs_to :scheduled_delivery
belongs_to :delivery
after_create :reload
validates_presence_of :model, :serial, :brand
scope :sold, -> { where(sold: true) }
scope :unsold, -> { where(sold: false) }
def address
scheduled_delivery.address
end
def is_scheduled
self.scheduled_delivery_id.present? && self.delivery_id.nil?
end
def is_delivered
self.delivery_id.nil?
end
def is_sold?
self.sold
end
end
|
module PageHelper
def footer_images
(Dir.entries("./app/assets/images/footer") - [".", ".."]).shuffle[0..3]
end
def napi_images(page)
(Dir.entries("./app/assets/images/napi") - [".", ".."])[(page-1)*10...(page)*10]
end
def name_list
[{:home => "Home"},
{:about=> "History", :past=>"Past internships"},
{:application=>"Application",:guidelines=>"Guidelines", :laboratories=>"Laboratories", :download=>"Downloads"},
{:travel=>"Travel"},
{:post=>"Post internship"},
{:faq=>"FAQ"},
{:contact=>"Contact"}
]
end
def load_post(name)
post = Content.where("title = ?", name).first
return BlueCloth.new(post.post).to_html if post
return "Hey, i think you forgot to add content for #{name}!"
end
end
|
require "spec_helper.rb"
describe "Deleting todo_item" do
let!(:todo_list) {TodoList.create(title: "Grocery list", description: "Groceries")}
let!(:todo_item) {todo_list.todo_items.create(content: "Milk")}
def delete_todo_item
within(dom_id_for(todo_item)) do
click_link "Delete"
end
end
it "succesfully deletes todo item" do
visit_todo_list(todo_list)
delete_todo_item
expect(page).to have_content("Succesfully deleted todo item")
expect(TodoItem.count).to eq(0)
end
end
|
#Magic 8-Ball
##Objective
#Use methods to keep our code DRY.
##Instructions
#Build a ruby program that when run will ask the user if they want to shake the eight ball.
#If the user answers yes, have it give a random message.
#If the user says no, have it end.
class Eightball
def initialize
@messages = [
"It is certain",
"It is decidedly so",
"Without a doubt",
"Yes definitely",
"You may rely on it",
"As I see it yes",
"Most likely",
"Signs point to yes",
"Ask again later",
"Better not tell you now",
"Concentrate and ask again",
"Don't count on it",
"My reply is no",
"My sources say no",
"Outlook not so good",
"Very doubtful"
]
@shake = ""
puts "Do you want to shake my magic eightball? (y/n)"
end
def shake
@shake = gets.chomp
case
when @shake == "y"
puts "What is your question?"
question = gets.chomp
puts "The magic eightball says, '#{@messages[rand(0..16)]}'"
puts "Shake again? (y/n)"
shake
when @shake == "n"
puts "Okay fine, have a nice day."
else
puts "That's not an option. Please select y/n."
shake
end
end
end
Eightball.new.shake |
require 'goby'
module Goby
# Can be worn in the Player's outfit.
class Shield < Item
include Equippable
# @param [String] name the name.
# @param [Integer] price the cost in a shop.
# @param [Boolean] consumable upon use, the item is lost when true.
# @param [Boolean] disposable allowed to sell or drop item when true.
# @param [Hash] stat_change the change in stats for when the item is equipped.
def initialize(name: "Shield", price: 0, consumable: false, disposable: true, stat_change: {})
super(name: name, price: price, consumable: consumable, disposable: disposable)
@type = :shield
@stat_change = stat_change
end
attr_reader :type, :stat_change
end
end |
require 'RSpec'
require_relative '../lexiconomitron.rb'
RSpec.describe "Lexiconomitron" do
describe "#eat_t" do
it "returns the same string if there is no t" do
@lexi = Lexiconomitron.new
expect(@lexi.eat_t("a")).to eq("a")
end
it "returns an empty string if the input is t" do
@lexi = Lexiconomitron.new
expect(@lexi.eat_t("t")).to eq("")
end
it "removes every letter t from the input" do
@lexi = Lexiconomitron.new
expect(@lexi.eat_t("great scott!")).to eq("grea sco!")
end
it "removes every letter T from the input" do
@lexi = Lexiconomitron.new
expect(@lexi.eat_t("Time to code!")).to eq("ime o code!")
end
end
describe "#reverse_string_in_array" do
it "returns the input reversed" do
@lexi = Lexiconomitron.new
expect(@lexi.reverse_string_in_array(["test"])).to eq(["tset"])
end
end
describe "#first_and_last_word" do
it "It returns the first and last word of an array" do
@lexi = Lexiconomitron.new
expect(@lexi.first_and_last_word(["a","b","c"])).to eq(["a","c"])
end
end
describe "#shazam" do
it "returns the first and last item in the input reversed and without t's" do
@lexi = Lexiconomitron.new
expect(@lexi.shazam(["test", "tom", "second", "class"])).to eq(["se", "ssalc"])
end
end
describe "#three_or_less" do
it "It takes an array and returns the words with length of three or less" do
@lexi = Lexiconomitron.new
expect(@lexi.three_or_less(["if","you","wanna","be","my","lover"])).to eq(["if","you","be","my"])
end
end
describe "#oompa_loompa" do
it "It takes an array and returns the words with length of three or less without t's" do
@lexi = Lexiconomitron.new
expect(@lexi.oompa_loompa(["if","you","wanna","be","my","lover", "tea"])).to eq(["if","you","be","my", "ea"])
end
end
end
|
module DelayedCell
class Queue
def initialize(target)
@target = target
@jobs = []
@worker = Worker.new target, self
end
def push(job)
@jobs << job
@worker.async.start
end
def pop
@jobs.shift
end
end
end
|
def disp_plans(plans)
puts "旅行プランを選択して下さい。"
plans.each.with_index(1) do |plan,i|
puts "#{i}. #{plan[:place]}旅行(#{plan[:price]}円)"
end
end
def choose_plan(plans)
while true
print "プランの番号を選択 > "
plan_num = gets.to_i
break if (1..3).include?(plan_num)
puts "1〜3の番号を入力して下さい。"
end
plans[plan_num - 1]
end
def decide_number_of_people(chosen_plan)
puts "#{chosen_plan[:place]}旅行ですね。"
puts "何名で予約されますか?"
while true
print "人数を入力 > "
member = gets.to_i
break if member >= 1
puts "1以上を入力して下さい。"
end
member
end
def calculate_total_charges(chosen_plan,number_of_people)
puts "#{number_of_people}名ですね。"
total_charges = chosen_plan[:price] * number_of_people
if number_of_people >= 5
puts "5名以上ですので10%割引となります"
total_charges *= 0.9
end
puts "合計金額は#{total_charges.floor}円になります。"
end |
require 'spec_helper'
class TestDocument < Document
field :content, type: String, default: ""
track_history on: :content, track_create: false
end
describe Document do
# describe 'lock checking' do
# it "starts out with a version of 1" do
# doc = TestDocument.create
# expect(doc.version).to eq 1
# end
# it "bumps the version when it's updated" do
# doc = TestDocument.create
# doc.update_attributes content: "Foo"
# expect(doc.version).to eq 2
# end
# it "raises an StaleDocument exception if someone else has updated it" do
# doc = TestDocument.create
# d1 = TestDocument.first
# d1.update_attributes content: "Foo"
# expect {doc.update_attributes(content: "Bar")}.to raise_error(StaleDocument)
# end
# end
end
|
require "spec_helper"
describe UserImagesController do
let(:user) { users(:no_picture) }
before do
log_in user
any_instance_of(User) do |any_user|
stub(any_user).save_attached_files { true }
end
end
describe "#create" do
context("for User") do
let(:files) { [Rack::Test::UploadedFile.new(File.expand_path("spec/fixtures/small1.gif", Rails.root), "image/gif")] }
it "returns success" do
post :create, :user_id => user.id, :files => files
response.should be_success
end
it "updates the user's image" do
default_image_path = "/images/default-user-icon.png"
user.image.url.should == default_image_path
post :create, :user_id => user.id, :files => files
user.reload
user.image.url.should_not == default_image_path
end
it "responds with the urls of the new image" do
post :create, :user_id => user.id, :files => files
user.reload
decoded_response.original.should == user.image.url(:original)
decoded_response.icon.should == user.image.url(:icon)
end
generate_fixture "image.json" do
post :create, :user_id => user.id, :files => files
end
end
end
describe "#show" do
let(:user) { users(:with_picture) }
it "uses send_file" do
mock(controller).send_file(user.image.path('original'), :type => user.image_content_type) {
controller.head :ok
}
get :show, :user_id => user.id
response.code.should == "200"
decoded_response.type == "image/gif"
end
context "when no image exists for the user" do
it "responds with a 404" do
get :show, :user_id => users(:admin)
response.code.should == "404"
end
end
end
end
|
require 'rails_helper'
RSpec.describe "phrases/index", type: :view do
before(:each) do
assign(:phrases, [
Phrase.create!(
:value => "MyText",
:keyphrase => nil
),
Phrase.create!(
:value => "MyText",
:keyphrase => nil
)
])
end
it "renders a list of phrases" do
render
assert_select "tr>td", :text => "MyText".to_s, :count => 2
assert_select "tr>td", :text => nil.to_s, :count => 2
end
end
|
class Tag < ApplicationRecord
has_many :post_taggings
has_many :posts, through: :post_taggings
validates :name, presence: true
validates :name, uniqueness: true
end
|
class Raindrops
def self.is_factor?(number, prime)
(number % prime).zero?
end
def self.convert(number)
output = ''.tap do |output|
{
3 => 'Pling',
5 => 'Plang',
7 => 'Plong'
}.each do |prime, sound|
output << sound if is_factor?(number, prime)
end
end
output.size == 0 ? number.to_s : output
end
end
|
FactoryGirl.define do
factory :suggestion do
location_name 'Apple Inc.'
latitude 37.331741
longitude(-122.030333)
address '1 Infinite Loop'
formatted_address "1 Infinite Loop\nCupertino, CA 95014"
city 'Cupertino'
state 'CA'
experience_name 'Visit Apple Headquarters!'
description 'So you can try and meet Jony Ive'
end
end
|
class UpdateContractsController < ApplicationController
before_action :authenticate_consultant!
def skip
session[:skip_update_contract] = true
redirect_to after_sign_in_path_for(current_consultant), notice: "Please remember to update your contract later."
end
def new
@contract = Contract.for_consultant(current_consultant)
@contract.updating_contract = true
@form = EditConsultantForm.new current_consultant
end
def update
current_consultant.contract_effective_date = DateTime.now
current_consultant.contract_version = Consultant::CURRENT_CONTRACT_VERSION
@form = EditConsultantForm.new current_consultant
@form.save
redirect_to after_sign_in_path_for(current_consultant), notice: "Thank you for updating your contract."
end
end
|
module MongoDoc
class InvalidEmbeddedHashKey < RuntimeError; end
module Associations
class HashProxy
include ProxyBase
HASH_METHODS = (Hash.instance_methods - Object.instance_methods).map { |n| n.to_s }
MUST_DEFINE = %w[to_a inspect to_bson ==]
DO_NOT_DEFINE = %w[merge! replace store update]
(HASH_METHODS + MUST_DEFINE - DO_NOT_DEFINE).uniq.each do |method|
class_eval <<-RUBY, __FILE__, __LINE__ + 1
def #{method}(*args, &block) # def each(*args, &block)
hash.send(:#{method}, *args, &block) # hash.send(:each, *args, &block)
end # end
RUBY
end
attr_reader :hash
%w(_modifier_path _selector_path).each do |setter|
class_eval <<-RUBY, __FILE__, __LINE__ + 1
def #{setter}=(path)
super
hash.each do |key, doc|
doc.#{setter} = #{setter} + '.' + key.to_s if ProxyBase.is_document?(doc)
end
end
RUBY
end
def initialize(options)
@hash = {}
super
end
alias put []=
def []=(key, value)
raise InvalidEmbeddedHashKey.new("Key name [#{key}] must be a valid element name, see http://www.mongodb.org/display/DOCS/BSON#BSON-noteonelementname") unless valid_key?(key)
put(key, attach(key, value))
end
alias store []=
def build(key, attrs)
item = _assoc_class.new(attrs)
store(key, item)
end
# Lie about our class. Borrowed from Rake::FileList
# Note: Does not work for case equality (<tt>===</tt>)
def is_a?(klass)
klass == Hash || super(klass)
end
alias kind_of? is_a?
def merge!(other)
other.each_pair do |key, value|
self[key] = if block_given?
yield key, [key], value
else
value
end
end
end
alias update merge!
def replace(other)
clear
merge!(other)
end
def valid?
values.all? do |child|
if ProxyBase.is_document?(child)
child.valid?
else
true
end
end
end
protected
def attach(key, value)
if ProxyBase.is_document?(value)
proxy = DocumentProxy.new(:path => _selector_path, :assoc_name => key, :root => _root, :parent => self)
proxy.document = value
proxy
else
value
end
end
def valid_key?(key)
(String === key or Symbol === key) and key.to_s !~ /(_id|query|\$.*|.*\..*)/
end
end
end
end
|
class CreatePermissions < ActiveRecord::Migration[5.1]
def change
create_table :permissions do |t|
t.string :kind, null: false, default: :user
t.belongs_to :user, null: false
t.string :permitted_actions, null: false
end
add_index :permissions, %i[kind user_id], unique: true
end
end
|
describe Spree::ShippingMatrixCalculator do
let(:variant1) { build(:variant, price: 10) }
let(:variant2) { build(:variant, price: 20) }
let(:role) { create(:role) }
let(:user) { create(:user, spree_roles: [role]) }
let (:package) { build(:stock_package, variants_contents: { variant1 => 4, variant2 => 6 }) }
before(:each) do
package.contents.first.inventory_unit.order.update(user: user)
end
context '#compute' do
subject { described_class.new(preferred_matrix_id: matrix.id).compute(package).to_f }
context 'when matrix has no rules' do
let(:matrix) { create(:shipping_matrix) }
it { is_expected.to eq(0.0) }
end
context 'when matrix has rules' do
let(:matrix) { create(:shipping_matrix_with_rules, num_of_rules: 5) }
let(:highest_min_line_item_total) do
create(:shipping_matrix_rule, min_line_item_total: 100, role: role)
end
let(:rule_with_matching_role) { highest_min_line_item_total }
before(:each) { matrix.rules << highest_min_line_item_total }
context 'and a rule with highest matching min line item total has amount of 4.99' do
before(:each) { highest_min_line_item_total.update!(amount: 4.99) }
it { is_expected.to eq(highest_min_line_item_total.amount.to_f) }
end
context 'and two rules with the same highest min line item total match' do
let(:another_rule) { create(:shipping_matrix_rule, min_line_item_total: 100) }
before(:each) { matrix.rules << another_rule }
context 'but only one rule#role matches and has amount of 3.99' do
before(:each) do
rule_with_matching_role.update!(amount: 3.99)
another_rule.update!(amount: 4.99)
end
it { is_expected.to eq(rule_with_matching_role.amount.to_f) }
end
context 'and both roles match' do
let(:matching_roles) { [rule_with_matching_role, another_rule] }
before(:each) do
rule_with_matching_role.update!(amount: 4.99)
another_rule.update!(role: role, amount: 3.99)
end
it 'should equal #amount from first matching role' do
is_expected.to eq(matching_roles.first.amount.to_f)
end
end
end
context 'and the order is a guest checkout' do
before(:each) do
package.contents.first.inventory_unit.order.update(user: nil, email: 'e@e.com')
end
let(:first_entry_rule) do
create(:shipping_matrix_rule, matrix: matrix, role: create(:role, name: 'entry'))
end
it 'should equal first rule matching #min_line_item_total and #role name is "entry"' do
is_expected.to eq(first_entry_rule.amount.to_f)
end
end
end
end
end
|
class CreateClimbSessions < ActiveRecord::Migration[5.0]
def change
create_table :climb_sessions do |t|
t.integer :host_id
t.integer :guest_id
t.integer :gym_id
t.text :notes
t.timestamps
end
end
end
|
module ApplicationHelper
def bootstrap_alert_class(type)
case type
when 'notice'
'success'
when 'alert'
'danger'
else
type
end
end
def page_title(title)
content_for :title, title
title
end
end
|
require 'spec_helper'
require_relative 'pipeline_helper'
describe RailsPipeline::IronmqPublisher do
before do
@default_emitter = DefaultIronmqEmitter.new({foo: "baz"}, without_protection: true)
end
it "should call post for IronMQ" do
expect_any_instance_of(IronMQ::Queue).to receive(:post) { |instance, serialized_encrypted_data|
base64_decoded_data = Base64.strict_decode64(JSON.parse(serialized_encrypted_data)['payload'])
encrypted_data = RailsPipeline::EncryptedMessage.parse(base64_decoded_data)
serialized_payload = DefaultEmitter.decrypt(encrypted_data)
data = DefaultEmitter_1_0.parse(serialized_payload)
expect(instance.name).to eq("harrys-#{Rails.env}-v1-default_emitters")
expect(encrypted_data.type_info).to eq(DefaultEmitter_1_0.to_s)
expect(data.foo).to eq("baz")
}.once
@default_emitter.emit
end
it "should actually publish message to IronMQ" do
@default_emitter.emit
@default_emitter.emit
@default_emitter.emit
@default_emitter.emit
@default_emitter.emit
@default_emitter.emit
@default_emitter.emit
@default_emitter.emit
@default_emitter.emit
end
end
|
# Дополнительное поле в тикете
class TicketField < ActiveRecord::Base
has_paper_trail
default_scope order("#{table_name}.name asc")
has_many :ticket_field_relations
has_many :ticket_questions, through: :ticket_field_relations
attr_accessible :name, :required, :hint, as: :admin
validates :name, presence: true
after_create :create_ticket_relations
state_machine initial: :active do
state :active
state :closed
event :close do
transition active: :closed
end
end
def hint
self[:hint].blank? ? nil : self[:hint]
end
def link_name
name
end
private
def create_ticket_relations
TicketQuestion.all.each do |ticket_question|
ticket_field_relations.create! do |ticket_field_relation|
ticket_field_relation.ticket_question = ticket_question
end
end
end
end
|
class UsersController < ApplicationController
before_filter :action_path
def action_path; @action = params[:action].dup.prepend("can_").concat("?").to_sym end
def authorized?(resource) error_redirect unless resource.send(@action,current_member,@team.id) end
before_filter :read_path
def read_path
@team = Team.find_by_id(params[:team_id])
redirect_to teams_path, alert: "Team #{params[:team_id]} does not exist" if @team.nil?
@server = Server.find_by_id(params[:server_id])
redirect_to team_path(@team), alert: "Server #{params[:server_id]} does not exist" if @server.nil?
@service = Service.find_by_id(params[:service_id])
redirect_to team_server_path(@team,@server), alert: "Service #{params[:service_id]} does not exist" if @service.nil? && params[:action] != 'modal'
end
def show
@user = User.find_by_id(params[:id])
authorized?(@user)
end
def new
error_redirect unless User.can_new?(current_member,@team.id)
@user = User.new
end
def edit
@user = User.find_by_id(params[:id])
authorized?(@user)
end
def csv
@action = :can_edit?
if params[:csv]
csv = params[:csv]
users_list = Array.new
users = User.where(service_id: @service.id)
authorized?(users)
passed = Array.new
unknown = Array.new
failed = Array.new
csv.gsub!(/(\r?\n)+/,"\r\n")
csv.split.each do |csv_user|
split = csv_user.split(',',2)
users_list << { username: split.first, password: split.last }
end
users_list.each do |hash|
username = hash[:username]
password = hash[:password]
user = users.where('username = ?', username).first
if user
user.update_attributes(password: password)
if user.save
passed << username
else
failed << "#{username} [#{user.errors.full_messages.join(',')}]"
end
else
unknown << username
end
end
flash.now[:success] = "Updated: #{passed.join(', ')}" unless passed.empty?
flash.now[:error] = "Failed: #{failed.join(', ')}" unless failed.empty?
flash.now[:info] = "Unknown username: #{unknown.join(', ')}" unless unknown.empty?
end
@users = User.where(service_id: @service.id)
authorized?(@users)
end
def create
@user = User.new(params[:user])
authorized?(@user)
if @user.save
redirect_to team_server_service_path(@team,@server,@service), notice: 'User was successfully created'
else
render action: "new"
end
end
def update
@user = User.find_by_id(params[:id])
authorized?(@user)
username = params[:user][:username] if params[:user][:username]
params[:user][:username] ? username = params[:user][:username] : username = nil
if Blueteam.can_update_usernames || username == @user.username || username.nil?
if @user.update_attributes(params[:user])
redirect_to team_server_service_path(@team,@server,@service), notice: 'User was successfully updated'
else
render action: "edit"
end
else
flash.now[:warning] = "Cannot change usernames"
render action: "edit"
end
end
def destroy
@user = User.find_by_id(params[:id])
authorized?(@user)
@user.destroy
redirect_to team_server_service_path(@team,@server,@service), notice: 'User was successfully deleted'
end
layout false, only: [:modal]
def modal
@action = :can_show?
@users = @service ? @service.users : @server.users
current_member.can_overview_users? || authorized?(@users)
@users.count == 0 ? render(partial: 'modal_empty') : render(partial: 'modal_users')
end
end
|
class CounselorSupervisor < ActiveRecord::Base
attr_accessible :employee_id, :employee_department_id, :employee_position_id
belongs_to :employee
belongs_to :employee_department
has_many :batch_counselor_supervisors
def to_label
employee.to_label
end
end
|
class BlocksController < ApplicationController
before_filter :authenticate_user!
before_filter :is_admin?
# GET /blocks
# GET /blocks.json
def index
@blocks = Block.order(:block_name).all
respond_to do |format|
format.html # index.html.erb
format.json { render :json => @blocks }
end
end
# GET /blocks/1/edit
def edit
@block = Block.find(params[:id])
respond_to do |format|
format.html
end
end
# PUT /blocks/1
# PUT /blocks/1.json
def update
@block = Block.find(params[:id])
respond_to do |format|
if @block.update_attributes(params[:block])
format.html { redirect_to blocks_path, :notice => 'Блок успешно обновлен' }
format.mobile { redirect_to blocks_path, :notice => 'Блок успешно обновлен' }
format.json { head :ok }
else
format.html { render :action => "edit" }
format.mobile { render :action => "edit" }
format.json { render :json => @block.errors, :status => :unprocessable_entity }
end
end
end
end
|
require 'spec_helper'
require 'deepstruct'
require 'pebblebed/config'
require 'pebblebed/connector'
require 'pebblebed/security/role_schema'
describe Pebblebed::Security::RoleSchema do
class InvalidRoleSchema < Pebblebed::Security::RoleSchema
role :guest, :capabilities => [], :requirements => []
role :contributor, :capabilities => [:comment, :kudo], :requirements => [:logged_in]
end
class CustomRoleSchema < Pebblebed::Security::RoleSchema
role :guest, :capabilities => [], :requirements => []
role :identified, :capabilities => [:kudo], :requirements => [:logged_in]
role :contributor, :capabilities => [:comment], :requirements => [:logged_in, :verified_mobile]
def check_logged_in
return true if identity and identity['identity']
false
end
def check_verified_mobile
return true if identity and identity['identity'] and identity['identity']['verified_mobile']
false
end
end
let(:connector) {
Pebblebed::Connector.new("session_key")
}
let(:guest) {
DeepStruct.wrap({})
}
let(:contributor) {
DeepStruct.wrap(:identity => {:realm => 'testrealm', :id => 1, :god => false})
}
let(:contributor_with_mobile) {
DeepStruct.wrap(:identity => {:realm => 'testrealm', :id => 1, :god => false, :verified_mobile => true})
}
context "invalid role schema" do
let(:schema) {
InvalidRoleSchema.new(connector, guest)
}
it "raises a NoMethodError with explaination about what you need to implement" do
expect {
schema.role
}.to raise_error(NoMethodError, "You must implement method named :check_logged_in that returns true or false")
end
end
context "basics" do
let(:schema) {
CustomRoleSchema.new(connector, guest)
}
it "has connector and identity attributes" do
expect(schema.connector).to eq connector
expect(schema.identity).to eq guest
end
it "has the correct roles defined" do
expect(CustomRoleSchema.roles).to eq([{:capabilities=>[], :requirements=>[], :name=>:guest, :role_rank=>0, :upgrades=>{:kudo=>[:logged_in], :comment=>[:logged_in, :verified_mobile]}}, {:capabilities=>[:kudo], :requirements=>[:logged_in], :name=>:identified, :role_rank=>1}, {:capabilities=>[:comment], :requirements=>[:logged_in, :verified_mobile], :name=>:contributor, :role_rank=>2}])
end
it "has an answer to requirements for a role" do
expect(CustomRoleSchema.requirements_for_role(:identified)).to eq([:logged_in])
expect(CustomRoleSchema.requirements_for_role(:contributor)).to eq([:logged_in, :verified_mobile])
end
it "gives a exception when the role is not found" do
expect {
CustomRoleSchema.requirements_for_role(:foo)
}.to raise_error(Pebblebed::Security::RoleSchema::UndefinedRole)
end
end
context "as guest" do
let(:schema) {
CustomRoleSchema.new(connector, guest)
}
it "returns the guest role" do
expect(schema.role).to eq({:current=>:guest, :capabilities=>[], :upgrades=>{:kudo=>[:logged_in], :comment=>[:logged_in, :verified_mobile]}})
end
end
context "as contributor" do
context "with a contributor without verified mobile" do
let(:schema) {
CustomRoleSchema.new(connector, contributor)
}
it "returns the idenitified role with an upgrade for :verified_mobile only" do
expect(schema.role).to eq({:current=>:identified, :capabilities=>[:kudo], :upgrades=>{:comment=>[:verified_mobile]}})
end
end
context "with a contributor with a verified mobile" do
let(:schema) {
CustomRoleSchema.new(connector, contributor_with_mobile)
}
it "returns the contributor role" do
expect(schema.role).to eq({:current=>:contributor, :capabilities=>[:kudo, :comment], :upgrades=>{}})
end
end
end
end
|
# Cookbook Name:: kafka_console
# Recipe:: pkg_install.rb
#
# Copyright 2015, @WalmartLabs
#
# All rights reserved - Do Not Redistribute
# install kafka binary
payLoad = node.workorder.payLoad[:kafka].select { |cm| cm['ciClassName'].split('.').last == 'Kafka'}.first
Chef::Log.info("payload: #{payLoad.inspect.gsub("\n"," ")}" )
if payLoad.nil?
Chef::Log.error("kafka_metadata is missing.")
exit 1
end
Chef::Log.info("ciAttributes content: "+payLoad["ciAttributes"].inspect.gsub("\n"," "))
kafka_version = payLoad["ciAttributes"]["version"]
kafka_rpm = "kafka-#{kafka_version}.noarch.rpm"
cloud = node.workorder.cloud.ciName
mirror_url_key = "lola"
Chef::Log.info("Getting mirror service for #{mirror_url_key}, cloud: #{cloud}")
mirror_svc = node[:workorder][:services][:mirror]
mirror = JSON.parse(mirror_svc[cloud][:ciAttributes][:mirrors]) if !mirror_svc.nil?
base_url = ''
# Search for Kafka mirror
base_url = mirror[mirror_url_key] if !mirror.nil? && mirror.has_key?(mirror_url_key)
if base_url.empty?
Chef::Log.error("#{mirror_url_key} mirror is empty for #{cloud}.")
end
kafka_download = base_url + "#{kafka_rpm}"
execute "remove kafka" do
user "root"
exists = <<-EOF
rpm -qa | grep 'kafka'
EOF
command "rpm -e $(rpm -qa '*kafka*')"
only_if exists, :user => "root"
end
# download kafka
remote_file ::File.join(Chef::Config[:file_cache_path], "#{kafka_rpm}") do
owner "root"
mode "0644"
source kafka_download
action :create
end
# install kafka
execute 'install kafka' do
user "root"
cwd Chef::Config[:file_cache_path]
command "rpm -i #{kafka_rpm}"
end
kafka_manager_rpm = node['kafka_console']['console']['filename']
kafka_manager_download = base_url + "#{kafka_manager_rpm}"
# remove kafka-manager, if it has been installed
execute "remove kafka-manager" do
user "root"
exists = <<-EOF
rpm -qa | grep 'kafka-manager'
EOF
command "rpm -e $(rpm -qa 'kafka-manager*')"
only_if exists, :user => "root"
end
# download kafka-manager
remote_file ::File.join(Chef::Config[:file_cache_path], "#{kafka_manager_rpm}") do
owner "root"
mode "0644"
source kafka_manager_download
action :create
end
# install kafka-manager
execute 'install kafka-manager' do
user "root"
cwd Chef::Config[:file_cache_path]
command "rpm -i #{kafka_manager_rpm}"
end
# remove ganglia-web
execute "remove ganglia-web" do
user "root"
exists = <<-EOF
rpm -qa | grep 'ganglia-web*'
EOF
command "rpm -e $(rpm -qa 'ganglia-web*')"
only_if exists, :user => "root"
end
# remove ganglia-gmond, ganglia-gmetad, ganglia,
execute "remove ganglia*" do
user "root"
exists = <<-EOF
rpm -qa | grep 'ganglia*'
EOF
command "rpm -e $(rpm -qa 'ganglia*')"
only_if exists, :user => "root"
end
# remove php-gd.x86_64
execute "remove php-gd.x86_64" do
user "root"
exists = <<-EOF
rpm -qa | grep 'php-gd.x86_64'
EOF
command "rpm -e $(rpm -qa 'php-gd*')"
only_if exists, :user => "root"
end
# remove php-ZendFramework
execute "remove php-ZendFramework" do
user "root"
exists = <<-EOF
rpm -qa | grep 'php-ZendFramework'
EOF
command "rpm -e $(rpm -qa 'php-ZendFramework*')"
only_if exists, :user => "root"
end
# remove libconfuse
execute "remove libconfuse" do
user "root"
exists = <<-EOF
rpm -qa | grep 'libconfuse'
EOF
command "rpm -e $(rpm -qa 'libconfuse')"
only_if exists, :user => "root"
end
# remove rrdtool
execute "remove rrdtool" do
user "root"
exists = <<-EOF
rpm -qa | grep 'rrdtool'
EOF
command "rpm -e $(rpm -qa 'rrdtool')"
only_if exists, :user => "root"
end
# install libconfuse.x86_64, rrdtool.x86_64, php-ZendFramework, php-gd.x86_64
if ["redhat", "centos", "fedora"].include?(node["platform"])
yum_package "libconfuse.x86_64" do
action :install
end
yum_package "rrdtool.x86_64" do
action :install
end
yum_package "php-ZendFramework" do
action :install
end
yum_package "php-gd.x86_64" do
action :install
end
else
Chef::Log.error("we currently support redhat, centos, fedora. You are using some OS other than those.")
end
# download ganglia
ganglia_rpm = node['kafka_console']['ganglia']['filename']
ganglia_download = base_url + "#{ganglia_rpm}"
remote_file ::File.join(Chef::Config[:file_cache_path], "#{ganglia_rpm}") do
owner "root"
mode "0644"
source ganglia_download
action :create
end
# install ganglia
execute 'install ganglia' do
user "root"
cwd Chef::Config[:file_cache_path]
command "rpm -i #{ganglia_rpm}"
end
# download gmond
gmond_rpm = node['kafka_console']['gmond']['filename']
gmond_download = base_url + "#{gmond_rpm}"
remote_file ::File.join(Chef::Config[:file_cache_path], "#{gmond_rpm}") do
owner "root"
mode "0644"
source gmond_download
action :create
end
# install gmond
execute 'install gmond' do
user "root"
cwd Chef::Config[:file_cache_path]
command "rpm -i #{gmond_rpm}"
end
# download gmetad
gmetad_rpm = node['kafka_console']['gmetad']['filename']
gmetad_download = base_url + "#{gmetad_rpm}"
remote_file ::File.join(Chef::Config[:file_cache_path], "#{gmetad_rpm}") do
owner "root"
mode "0644"
source gmetad_download
action :create
end
# install gmetad
execute 'install gmetad' do
user "root"
cwd Chef::Config[:file_cache_path]
command "rpm -i #{gmetad_rpm}"
end
nginx_rpm = node['kafka_console']['nginx']['filename']
nginx_download = base_url + "#{nginx_rpm}"
# remove nginx, if it has been installed
execute "remove nginx" do
user "root"
exists = <<-EOF
rpm -qa | grep 'nginx'
EOF
command "rpm -e $(rpm -qa 'nginx*')"
only_if exists, :user => "root"
end
# download nginx
remote_file ::File.join(Chef::Config[:file_cache_path], "#{nginx_rpm}") do
owner "root"
mode "0644"
source nginx_download
action :create
end
# install nginx
execute 'install nginx' do
user "root"
cwd Chef::Config[:file_cache_path]
command "rpm -i #{nginx_rpm}"
end
# httpd should has been installed with every OneOps VM.
gweb_rpm = node['kafka_console']['gweb']['filename']
gweb_download = base_url + "#{gweb_rpm}"
remote_file ::File.join(Chef::Config[:file_cache_path], "#{gweb_rpm}") do
owner "root"
mode "0644"
source gweb_download
action :create
end
# install gweb
execute 'install gweb' do
user "root"
cwd Chef::Config[:file_cache_path]
command "rpm -i #{gweb_rpm}"
end
bash "move-and-chown" do
user "root"
code <<-EOF
(ln -s /usr/share/ganglia/ /var/www/html/gweb)
(chown -R apache:apache /var/www/html/gweb/)
EOF
end
|
class CreatePhotos < ActiveRecord::Migration
def up
create_table :photos do |t|
t.string :path
t.string :token
t.integer :file_size
t.integer :boost, default: 0
t.timestamps
end
add_index :photos, :token
end
def down
drop_table :photos
end
end
|
class Freezer < ApplicationRecord
has_many :items
has_and_belongs_to_many :users, {:join_table => :user_freezers}
validates :name, presence: true
accepts_nested_attributes_for :items
def number_of_items
self.items.count
end
def items_attributes=(items_attributes)
attr = items_attributes["0"]
if !attr[:title].blank?
item = Item.new(title: attr[:title], item_type_id: attr[:item_type_id])
item.date_stored = Chronic.parse(items_attributes["0"][:date_stored]).to_datetime
item.users << User.find_by(id: attr[:user_ids][0])
item.notes.build(attr[:note])
self.items << item
end
end
end
|
describe Pantograph do
describe Pantograph::PantFile do
describe "Opt Out Usage" do
it "works as expected" do
Pantograph::PantFile.new.parse("lane :test do
opt_out_usage
end").runner.execute(:test)
expect(ENV['PANTOGRAPH_OPT_OUT_USAGE']).to eq("YES")
end
end
end
end
|
# frozen_string_literal: true
require 'rails_helper'
RSpec.describe Readings::Find do
subject { described_class.run(params) }
let(:params) do
{
number: number,
household_token: thermostat.household_token
}
end
before do
allow(Rails.configuration.redis).to receive(:get).with("#{thermostat.household_token}.count") { '2' }
allow(Rails.configuration.redis).to receive(:get).with(thermostat.household_token) { json_reading }
end
let(:json_reading) { reading2.attributes.slice('temperature', 'humidity', 'battery_charge').to_json }
let(:thermostat) { create(:thermostat) }
let!(:reading1) { create(:reading, thermostat: thermostat, number: 1) }
let!(:reading2) { create(:reading, thermostat: thermostat, number: 2) }
context 'when the requested reading is stored in redis' do
let(:number) { 2 }
it 'uses redis to fetch it' do
expect(Rails.configuration.redis).to receive(:get).with(thermostat.household_token)
subject
end
end
context 'when the requested reading is not the last one' do
let(:number) { 1 }
it 'uses activerecord to fetch it' do
expect(Thermostat).to receive_message_chain(:find_by_household_token, :readings, :find_by_number)
subject
end
end
end
|
class LikesController < ApplicationController
# GET /likes
# GET /likes.json
def index
@likes = Like.all
respond_to do |format|
format.html # index.html.erb
format.json { render json: @likes }
end
end
# GET /likes/1
# GET /likes/1.json
# GET /likes/new
# GET /likes/new.json
# POST /likes
# POST /likes.json
def create
@showcase = Showcase.find(params[:like][:showcase_id])
if @title == nil
@showcases = Showcase.where('').paginate(page: params[:page], per_page: 6)
else
@showcases = Gallery.find(@showcase.gallery.id).showcases.paginate(page: params[:page], per_page: 6)
end
@user = @showcase.gallery.user
unless current_user == @user
current_user.like!(@showcase)
end
respond_to do |format|
format.html { redirect_to :back }
format.js
end
end
# PATCH/PUT /likes/1
# PATCH/PUT /likes/1.json
# DELETE /likes/1
# DELETE /likes/1.json
def destroy
print params[:id]
@showcase = Like.find(params[:id]).showcase
@showcases = Gallery.find(@showcase.gallery.id).showcases.paginate(page: params[:page], per_page: 6)
current_user.unlike!(@showcase)
respond_to do |format|
format.html { redirect_back }
format.js
end
end
private
# Use this method to whitelist the permissible parameters. Example:
# params.require(:person).permit(:name, :age)
# Also, you can specialize this method with per-user checking of permissible attributes.
def like_params
params.require(:like).permit(:showcase_id, :id)
end
end
|
# frozen_string_literal: true
module Diplomat
class KeyNotFound < StandardError; end
class PathNotFound < StandardError; end
class KeyAlreadyExists < StandardError; end
class AclNotFound < PathNotFound; end
class AclAlreadyExists < StandardError; end
class EventNotFound < StandardError; end
class EventAlreadyExists < StandardError; end
class QueryNotFound < StandardError; end
class QueryAlreadyExists < StandardError; end
class UnknownStatus < StandardError; end
class IdParameterRequired < StandardError; end
class NameParameterRequired < StandardError; end
class InvalidTransaction < StandardError; end
class DeprecatedArgument < StandardError; end
class PolicyNotFound < StandardError; end
class NameParameterRequired < StandardError; end
class PolicyMalformed < StandardError; end
class AccessorIdParameterRequired < StandardError; end
class TokenMalformed < StandardError; end
class PolicyAlreadyExists < StandardError; end
class RoleMalformed < StandardError; end
class RoleNotFound < StandardError; end
end
|
require 'pry'
class String
def sentence?
self[-1] == '.'
end
def question?
self[-1] == '?'
end
def exclamation?
self[-1] == '!'
end
def count_sentences
punctuation = ['.', '?', '!']
split_string = split(Regexp.union(punctuation))
split_string.delete('')
split_string.length
end
end
|
class Bishop < Piece
attr_reader :color, :type, :position
include SlidingPiece
def initialize(board=nil, position = nil, color)
@board = board
@position = position
@color = color
@type = :bi
@direction = [[1,1],[-1,1],[-1,-1],[1,-1]]
end
def move_dirs
@direction.dup
end
end
|
#this file demonstration of function declaration in ruby
#this is function defintion
#start of multiline comment
=begin
this is a multiline comment
structure of a function is
def keyword followed by function_name
body of function
end- denotes the end of function body
=end
#end of multiline comment
def func(param1)
puts "passed argument is " + param1
end
#in order to invoke the function just type the function name with arguments(optional)
func("arg1")
func("param1")
|
namespace :test do
desc 'run functional tests'
task :functional do
ruby './test/functional/suite.rb'
ruby './test/functional/for_redcloth.rb' unless (''.chop! rescue true)
end
desc 'run unit tests'
task :units do
ruby './test/unit/suite.rb'
end
scanner_suite = 'test/scanners/suite.rb'
desc 'run all scanner tests'
task :scanners => :update_scanner_suite do
ruby scanner_suite
end
desc 'update scanner test suite from GitHub'
task :update_scanner_suite do
if File.exist? scanner_suite
Dir.chdir File.dirname(scanner_suite) do
if File.directory? '.git'
puts 'Updating scanner test suite...'
sh 'git pull'
elsif File.directory? '.svn'
raise <<-ERROR
Found the deprecated Subversion scanner test suite in ./#{File.dirname(scanner_suite)}.
Please rename or remove it and run again to use the GitHub repository:
mv test/scanners test/scanners-old
ERROR
else
raise 'No scanner test suite found.'
end
end
else
puts 'Downloading scanner test suite...'
sh 'git clone https://github.com/rubychan/coderay-scanner-tests.git test/scanners/'
end unless ENV['SKIP_UPDATE_SCANNER_SUITE']
end
namespace :scanner do
Dir['./test/scanners/*'].each do |scanner|
next unless File.directory? scanner
lang = File.basename(scanner)
desc "run all scanner tests for #{lang}"
task lang => :update_scanner_suite do
ruby "./test/scanners/suite.rb #{lang}"
end
end
end
desc 'clean test output files'
task :clean do
for file in Dir['test/scanners/**/*.actual.*']
rm file
end
for file in Dir['test/scanners/**/*.debug.diff']
rm file
end
for file in Dir['test/scanners/**/*.debug.diff.html']
rm file
end
for file in Dir['test/scanners/**/*.expected.html']
rm file
end
end
desc 'test the CodeRay executable'
task :exe do
if RUBY_VERSION >= '1.8.7'
ruby './test/executable/suite.rb'
else
puts
puts "Can't run executable tests because shoulda-context requires Ruby 1.8.7+."
puts "Skipping."
end
end
end
if RUBY_VERSION >= '1.9'
require 'rspec/core/rake_task'
RSpec::Core::RakeTask.new(:spec)
end
task :test => %w(test:functional test:units test:exe spec)
|
# frozen_string_literal: true
class Article < ApplicationRecord
has_many :comments, dependent: :destroy
belongs_to :user
validates :title, presence: true,
length: { minimum: 5 }
validates :text, presence: true,
length: { maximum: 141 }
end
|
require 'spec_helper'
describe PaypalDetailsController do
after(:all) do
PaypalDetail.delete_all
User.delete_all
end
before(:each) do
@request.env["devise.mapping"] = Devise.mappings[:user]
@user = FactoryGirl.create(:user)
FactoryGirl.create(:configuration_setting)
@user.confirm! # set a confirmed_at inside the factory. Only necessary if you are using the confirmable module
sign_in @user
end
describe "GET #index" do
it "should redirect to new paypal detail" do
@paypal = FactoryGirl.create(:paypal_detail)
end
it "renders the :index view" do
get :index
response.should redirect_to new_paypal_detail_path
end
end
describe "POST create" do
context "with valid attributes" do
it "creates a new paypaldetail" do
expect{
post :create, paypal_detail: FactoryGirl.attributes_for(:paypal_detail)
}.to change(PaypalDetail,:count).by(1)
end
it "redirects to the new paypaldetail" do
post :create, paypal_detail: FactoryGirl.attributes_for(:paypal_detail)
response.should redirect_to payment_details_url
end
end
context "with invalid attributes" do
it "creates a new paypaldetail" do
expect{
post :create, paypal_detail: FactoryGirl.attributes_for(:paypal_detail, :email=>"tester@test.com")
}.to_not change(PaypalDetail,:count)
end
it "should raise errors and redirect to payment url" do
paypal_detail = FactoryGirl.build(:paypal_detail, :email=>"tester@test.com")
post :create, paypal_detail: FactoryGirl.attributes_for(:paypal_detail, :email=>"tester@test.com")
response.should redirect_to payment_details_url
end
end
end
describe 'DELETE destroy' do
before :each do
@paypal_detail = FactoryGirl.create(:paypal_detail)
end
it "deletes the product" do
expect{
delete :destroy, id: @paypal_detail
}.to change(PaypalDetail,:count).by(-1)
end
it "redirects to products#index" do
delete :destroy, id: @paypal_detail
response.should redirect_to payment_details_url
end
end
#=============================================fail case==================================
describe "GET #index" do
it "should redirect to new paypal detail" do
@paypal = FactoryGirl.create(:paypal_detail)
end
it "renders the :index view" do
get :index
response.should_not redirect_to new_paypal_detail_path
end
end
describe "POST create" do
context "with valid attributes" do
it "creates a new paypaldetail" do
expect{
post :create, paypal_detail: FactoryGirl.attributes_for(:paypal_detail)
}.to_not change(PaypalDetail,:count).by(1)
end
it "redirects to the new paypaldetail" do
post :create, paypal_detail: FactoryGirl.attributes_for(:paypal_detail)
response.should_not redirect_to payment_details_url
end
end
context "with invalid attributes" do
it "creates a new paypaldetail" do
expect{
post :create, paypal_detail: FactoryGirl.attributes_for(:paypal_detail, :email=>"tester@test.com")
}.to_not change(PaypalDetail,:count)
end
it "should raise errors and redirect to payment url" do
paypal_detail = FactoryGirl.build(:paypal_detail, :email=>"tester@test.com")
post :create, paypal_detail: FactoryGirl.attributes_for(:paypal_detail, :email=>"tester@test.com")
response.should_not redirect_to payment_details_url
end
end
end
describe 'DELETE destroy' do
before :each do
@paypal_detail = FactoryGirl.create(:paypal_detail)
end
it "deletes the product" do
expect{
delete :destroy, id: @paypal_detail
}.to_not change(PaypalDetail,:count).by(-1)
end
it "redirects to products#index" do
delete :destroy, id: @paypal_detail
response.should_not redirect_to payment_details_url
end
end
end
|
module Api
module V1
class Api::V1::FlightsController < Api::V1::ApplicationController
def index
@flights = Flight.includes(:rocket).order(launched_at: :desc).all
@flights = @flights.filter_reddit_links if params[:with_reddit] == "1"
@flights = @flights.filter_successful_launches if params[:with_successful_launches] == "1"
@flights = @flights.filter_reuses if params[:with_reuses] == "1"
render json: FlightSerializer.new(@flights)
end
private
def filter_params
params.permit(:with_reddit_links)
params.permit(:with_successful_launches)
params.permit(:with_reuses)
end
end
end
end |
require 'lib/fraccionarios'
require 'test/unit'
class TestFraccionario < Test::Unit::TestCase
def setup
@numero_fraccionario_1 = Numero_Fraccionario.new(10,5)
@numero_fraccionario_2 = Numero_Fraccionario.new(20,10)
end
def test_tos
assert_equal("10/5", @numero_fraccionario_1.to_s)
assert_equal("20/10", @numero_fraccionario_2.to_s)
end
def test_mcd
assert_equal(5, @numero_fraccionario_1.mcd(10,5))
assert_equal(8, @numero_fraccionario_1.mcd(40,8))
end
def test_mcm
assert_equal(5, @numero_fraccionario_1.mcm(5,1))
assert_equal(30, @numero_fraccionario_2.mcm(15,6))
end
def test_suma
assert_equal("40/10", (@numero_fraccionario_1 + @numero_fraccionario_2).to_s)
end
def test_resta
assert_equal("-45/10", (Numero_Fraccionario.new(50,10) - Numero_Fraccionario.new(5,10)).to_s)
end
def test_multiplicacion
assert_equal("200/50", (@numero_fraccionario_1 * @numero_fraccionario_2).to_s)
end
def test_division
assert_equal("100/100", (@numero_fraccionario_1 / @numero_fraccionario_2).to_s)
end
def test_simplificar
assert_equal("2/1", @numero_fraccionario_1.simplificar.to_s)
assert_equal("2/1", @numero_fraccionario_2.simplificar.to_s)
end
def test_negacion
num1_simplificado = @numero_fraccionario_1.simplificar
num1_simplificado = -num1_simplificado
assert_equal("-2/1", num1_simplificado.to_s)
end
def test_type_check
assert_raise(RuntimeError) {Numero_Fraccionario.new(1,'hola')}
assert_raise(RuntimeError) {Numero_Fraccionario.new('adios',1)}
end
def test_comparaciones
num1_simplificado = @numero_fraccionario_1.simplificar
num2_simplificado = @numero_fraccionario_2.simplificar
assert_equal(true, num1_simplificado.igual_que(num2_simplificado))
assert_equal(false, num1_simplificado.distinto_que(num2_simplificado))
assert_equal(false, num1_simplificado.menor_que(num2_simplificado))
assert_equal(false, num1_simplificado.mayor_que(num2_simplificado))
end
def test_tof
assert_equal(2, @numero_fraccionario_1.to_f)
end
def test_reciproco
num1_simplificado = @numero_fraccionario_1.simplificar
num1_simplificado = num1_simplificado.reciproco
assert_equal("1/2", num1_simplificado.to_s)
end
end
|
# compares RSS feeds
RSpec::Matchers.define :have_data_from do |internal_feed|
match do |actual_feed|
@errors = []
if actual_feed.channel.title !~ /#{internal_feed.username}/
@errors << "Feed title mismatch: expected: '#{actual_feed.channel.title}' to contain '#{internal_feed.username}'"
end
if actual_feed.items.size != internal_feed.entries.size
@errors << "Number of feed entries don't match: expected: '#{internal_feed.entries.size}' got: '#{actual_feed.items.size}'"
end
@errors.empty?
end
failure_message_for_should do
@errors.join("\n")
end
end
# compares feed objects
RSpec::Matchers.define :equal_to do |expected_feed|
match do |actual_feed|
@errors = []
if actual_feed.username != expected_feed.username
@errors < "Username mismatch: expected: #{expected_feed.username}, got: #{actual_feed.username}"
end
if actual_feed.entries != expected_feed.entries
@errors < "Entries mismatch: expected: #{expected_feed.entries}, got: #{actual_feed.entries}"
end
@errors.empty?
end
failure_message_for_should do
@errors.join("\n")
end
end
|
class AddColumnfToProfessionals < ActiveRecord::Migration
def change
add_column :professionals, :cv, :string
add_column :professionals, :cv_file_name, :string
add_column :professionals, :cv_content_type, :string
add_column :professionals, :cv_file_size, :integer
add_column :professionals, :cv_updated_at, :datetime
end
end
|
class Outpost::HomeController < Outpost::BaseController
def dashboard
breadcrumb "Dashboard", outpost.root_path
end
end |
module Catalog
class TopologyError < StandardError; end
class RBACError < StandardError; end
class ApprovalError < StandardError; end
class NotAuthorized < StandardError; end
class InvalidNotificationClass < StandardError; end
class InvalidParameter < StandardError; end
end
|
require "test_helper"
describe Order do
let(:o1) { orders(:o1) }
let(:oi1) { order_items(:oi1) }
let(:oi2) { order_items(:oi2) }
let(:p1) { products(:p1) }
let(:p2) { products(:p2) }
let (:empty_order) { Order.create() }
describe "RELATIONSHIPS" do
it "can have many order items" do
o1.order_items << oi1
o1.order_items << oi2
assert(o1.order_items.length > 1)
end
end
describe "default status" do
it "sets the status of an order to 'pending'" do
o1.status = nil
o1.default_status
expect(o1.status).must_equal "pending"
end
end
describe "get_grand_total" do
it "can get the grand total" do
total = 0
o1.order_items.each do |item|
total += item.subtotal
end
expect(o1.get_grand_total).must_equal total
end
it "returns a grand total of 0 for a cart with no items" do
o1.order_items.destroy_all
o1.reload
expect(o1.get_grand_total).must_equal 0
end
end
describe "missing_stock()" do
it "if no missing stock, return nil" do
expect(o1.missing_stock).must_be_nil
end
it "if has missing stock, return array of out of stock order_items" do
o1
expect(p1.stock).must_equal 5
expect(p2.stock).must_equal 2
p1.update!(stock: 0)
p2.update!(stock: 0)
assert(o1.missing_stock)
assert(o1.missing_stock.length == 2)
assert(o1.missing_stock.include? oi1)
assert(o1.missing_stock.include? oi1)
end
it "if order has no items, missing_stock() returns nil" do
expect(empty_order.missing_stock).must_be_nil
end
end
describe "names_from_order_items()" do
it "Can return string of order_item's product names" do
expect(o1.names_from_order_items([oi1, oi2])).must_equal "Product1, Product2"
expect(o1.names_from_order_items([oi1])).must_equal "Product1"
end
it "If order has 0 order_items, returns 'None'" do
expect(empty_order.names_from_order_items([])).must_equal "None"
end
it "If bogus argument used, returns expected error statement" do
expect(o1.names_from_order_items("garbage")).must_equal "Invalid argument, expecting an array of Order Item instances"
end
end
end
|
# == Schema Information
#
# Table name: course_phases
#
# id :integer not null, primary key
# subject_id :integer
# phase_id :integer
# created_at :datetime not null
# updated_at :datetime not null
#
require 'rails_helper'
RSpec.describe CoursePhase, type: :model do
context 'associations' do
it { should belong_to(:subject) }
it { should belong_to(:phase) }
end
context 'validations' do
it { should validate_presence_of :subject }
it { should validate_presence_of :phase }
end
it "has a valid factory" do
expect(build(:course_phase)).to be_valid
end
end
|
# Paperclip allows file attachments that are stored in the filesystem. All graphical
# transformations are done using the Graphics/ImageMagick command line utilities and
# are stored in Tempfiles until the record is saved. Paperclip does not require a
# separate model for storing the attachment's information, instead adding a few simple
# columns to your table.
#
# Author:: Jon Yurek
# Copyright:: Copyright (c) 2008-2011 thoughtbot, inc.
# License:: MIT License (http://www.opensource.org/licenses/mit-license.php)
#
# Paperclip defines an attachment as any file, though it makes special considerations
# for image files. You can declare that a model has an attached file with the
# +has_attached_file+ method:
#
# class User < ActiveRecord::Base
# has_attached_file :avatar, :styles => { :thumb => "100x100" }
# end
#
# user = User.new
# user.avatar = params[:user][:avatar]
# user.avatar.url
# # => "/users/avatars/4/original_me.jpg"
# user.avatar.url(:thumb)
# # => "/users/avatars/4/thumb_me.jpg"
#
# See the +has_attached_file+ documentation for more details.
require "erb"
require "digest"
require "tempfile"
require "paperclip/version"
require "paperclip/geometry_parser_factory"
require "paperclip/geometry_detector_factory"
require "paperclip/geometry"
require "paperclip/processor"
require "paperclip/processor_helpers"
require "paperclip/tempfile"
require "paperclip/thumbnail"
require "paperclip/interpolations/plural_cache"
require "paperclip/interpolations"
require "paperclip/tempfile_factory"
require "paperclip/style"
require "paperclip/attachment"
require "paperclip/storage"
require "paperclip/callbacks"
require "paperclip/file_command_content_type_detector"
require "paperclip/media_type_spoof_detector"
require "paperclip/content_type_detector"
require "paperclip/glue"
require "paperclip/errors"
require "paperclip/missing_attachment_styles"
require "paperclip/validators"
require "paperclip/logger"
require "paperclip/helpers"
require "paperclip/has_attached_file"
require "paperclip/attachment_registry"
require "paperclip/filename_cleaner"
require "paperclip/rails_environment"
begin
# Use mime/types/columnar if available, for reduced memory usage
require "mime/types/columnar"
rescue LoadError
require "mime/types"
end
require "marcel"
require "logger"
require "terrapin"
require "paperclip/railtie" if defined?(Rails::Railtie)
# The base module that gets included in ActiveRecord::Base. See the
# documentation for Paperclip::ClassMethods for more useful information.
module Paperclip
extend Helpers
extend Logger
extend ProcessorHelpers
# Provides configurability to Paperclip. The options available are:
# * whiny: Will raise an error if Paperclip cannot process thumbnails of
# an uploaded image. Defaults to true.
# * log: Logs progress to the Rails log. Uses ActiveRecord's logger, so honors
# log levels, etc. Defaults to true.
# * command_path: Defines the path at which to find the command line
# programs if they are not visible to Rails the system's search path. Defaults to
# nil, which uses the first executable found in the user's search path.
# * use_exif_orientation: Whether to inspect EXIF data to determine an
# image's orientation. Defaults to true.
def self.options
@options ||= {
command_path: nil,
content_type_mappings: {},
log: true,
log_command: true,
read_timeout: nil,
swallow_stderr: true,
use_exif_orientation: true,
whiny: true,
is_windows: Gem.win_platform?,
add_validation_errors_to: :both
}
end
def self.io_adapters=(new_registry)
@io_adapters = new_registry
end
def self.io_adapters
@io_adapters ||= Paperclip::AdapterRegistry.new
end
module ClassMethods
# +has_attached_file+ gives the class it is called on an attribute that maps to a file. This
# is typically a file stored somewhere on the filesystem and has been uploaded by a user.
# The attribute returns a Paperclip::Attachment object which handles the management of
# that file. The intent is to make the attachment as much like a normal attribute. The
# thumbnails will be created when the new file is assigned, but they will *not* be saved
# until +save+ is called on the record. Likewise, if the attribute is set to +nil+ is
# called on it, the attachment will *not* be deleted until +save+ is called. See the
# Paperclip::Attachment documentation for more specifics. There are a number of options
# you can set to change the behavior of a Paperclip attachment:
# * +url+: The full URL of where the attachment is publicly accessible. This can just
# as easily point to a directory served directly through Apache as it can to an action
# that can control permissions. You can specify the full domain and path, but usually
# just an absolute path is sufficient. The leading slash *must* be included manually for
# absolute paths. The default value is
# "/system/:class/:attachment/:id_partition/:style/:filename". See
# Paperclip::Attachment#interpolate for more information on variable interpolaton.
# :url => "/:class/:attachment/:id/:style_:filename"
# :url => "http://some.other.host/stuff/:class/:id_:extension"
# Note: When using the +s3+ storage option, the +url+ option expects
# particular values. See the Paperclip::Storage::S3#url documentation for
# specifics.
# * +default_url+: The URL that will be returned if there is no attachment assigned.
# This field is interpolated just as the url is. The default value is
# "/:attachment/:style/missing.png"
# has_attached_file :avatar, :default_url => "/images/default_:style_avatar.png"
# User.new.avatar_url(:small) # => "/images/default_small_avatar.png"
# * +styles+: A hash of thumbnail styles and their geometries. You can find more about
# geometry strings at the ImageMagick website
# (http://www.imagemagick.org/script/command-line-options.php#resize). Paperclip
# also adds the "#" option (e.g. "50x50#"), which will resize the image to fit maximally
# inside the dimensions and then crop the rest off (weighted at the center). The
# default value is to generate no thumbnails.
# * +default_style+: The thumbnail style that will be used by default URLs.
# Defaults to +original+.
# has_attached_file :avatar, :styles => { :normal => "100x100#" },
# :default_style => :normal
# user.avatar.url # => "/avatars/23/normal_me.png"
# * +keep_old_files+: Keep the existing attachment files (original + resized) from
# being automatically deleted when an attachment is cleared or updated. Defaults to +false+.
# * +preserve_files+: Keep the existing attachment files in all cases, even if the parent
# record is destroyed. Defaults to +false+.
# * +whiny+: Will raise an error if Paperclip cannot post_process an uploaded file due
# to a command line error. This will override the global setting for this attachment.
# Defaults to true.
# * +convert_options+: When creating thumbnails, use this free-form options
# array to pass in various convert command options. Typical options are "-strip" to
# remove all Exif data from the image (save space for thumbnails and avatars) or
# "-depth 8" to specify the bit depth of the resulting conversion. See ImageMagick
# convert documentation for more options: (http://www.imagemagick.org/script/convert.php)
# Note that this option takes a hash of options, each of which correspond to the style
# of thumbnail being generated. You can also specify :all as a key, which will apply
# to all of the thumbnails being generated. If you specify options for the :original,
# it would be best if you did not specify destructive options, as the intent of keeping
# the original around is to regenerate all the thumbnails when requirements change.
# has_attached_file :avatar, :styles => { :large => "300x300", :negative => "100x100" }
# :convert_options => {
# :all => "-strip",
# :negative => "-negate"
# }
# NOTE: While not deprecated yet, it is not recommended to specify options this way.
# It is recommended that :convert_options option be included in the hash passed to each
# :styles for compatibility with future versions.
# NOTE: Strings supplied to :convert_options are split on space in order to undergo
# shell quoting for safety. If your options require a space, please pre-split them
# and pass an array to :convert_options instead.
# * +storage+: Chooses the storage backend where the files will be stored. The current
# choices are :filesystem, :fog and :s3. The default is :filesystem. Make sure you read the
# documentation for Paperclip::Storage::Filesystem, Paperclip::Storage::Fog and Paperclip::Storage::S3
# for backend-specific options.
#
# It's also possible for you to dynamically define your interpolation string for :url,
# :default_url, and :path in your model by passing a method name as a symbol as a argument
# for your has_attached_file definition:
#
# class Person
# has_attached_file :avatar, :default_url => :default_url_by_gender
#
# private
#
# def default_url_by_gender
# "/assets/avatars/default_#{gender}.png"
# end
# end
def has_attached_file(name, options = {})
HasAttachedFile.define_on(self, name, options)
end
end
end
# This stuff needs to be run after Paperclip is defined.
require "paperclip/io_adapters/registry"
require "paperclip/io_adapters/abstract_adapter"
require "paperclip/io_adapters/empty_string_adapter"
require "paperclip/io_adapters/identity_adapter"
require "paperclip/io_adapters/file_adapter"
require "paperclip/io_adapters/stringio_adapter"
require "paperclip/io_adapters/data_uri_adapter"
require "paperclip/io_adapters/nil_adapter"
require "paperclip/io_adapters/attachment_adapter"
require "paperclip/io_adapters/uploaded_file_adapter"
require "paperclip/io_adapters/uri_adapter"
require "paperclip/io_adapters/http_url_proxy_adapter"
|
require "formula"
class Atk < Formula
homepage "http://library.gnome.org/devel/atk/"
url "http://ftp.gnome.org/pub/gnome/sources/atk/2.14/atk-2.14.0.tar.xz"
sha256 "2875cc0b32bfb173c066c22a337f79793e0c99d2cc5e81c4dac0d5a523b8fbad"
bottle do
revision 1
sha1 "5a014bce43ff14675bec23b61909d3d85cff20f1" => :yosemite
sha1 "f75b7b55547cb58c87fd35e38e8cdba0877516f8" => :mavericks
sha1 "8aa05a84f58854ba26258d0d206c4e2fb663eb16" => :mountain_lion
end
depends_on "pkg-config" => :build
depends_on "glib"
depends_on "gobject-introspection"
option :universal
def install
ENV.universal_binary if build.universal?
system "./configure", "--disable-dependency-tracking",
"--prefix=#{prefix}",
"--enable-introspection=yes"
system "make"
system "make install"
end
end
|
class LanguagesController < ApplicationController
before_action :logged_in?
before_action :current_user, only:[:create, :destroy]
def new_or_destroy
@language = Language.new
end
def create
if language_params[:name].empty? && language_params[:id].nil?
redirect_to new_or_delete_language_path
else
if !language_params[:name].empty?
@language = Language.find_or_create_by(name: language_params[:name])
else
@language = Language.find_by_id(language_params[:id])
end
@current_user.languages << @language if @language && !@current_user.languages.include?(@language)
redirect_to user_path(@current_user)
end
end
def destroy
@languages = language_delete_params[:id]
@languages.delete("")
@languages.each do |lang_id|
language = Language.find_by_id(lang_id)
@current_user.languages.destroy(language)
end
redirect_to user_path(@current_user)
end
private
def language_params
params.require(:language).permit(:name, :id)
end
# validates id params to accept an array of ids to be deleted at the same time
def language_delete_params
params.require(:language).permit(:id => [])
end
end
|
require 'devise'
require 'rails'
DEVISE_PATH = File.expand_path(File.join(File.dirname(__FILE__), '..', '..'))
module Devise
class Railtie < Rails::Railtie
railtie_name :devise
def load_paths
Dir["#{DEVISE_PATH}/app/{mailers,controllers,helpers}"]
end
# TODO: 'after' and 'before' hooks appear to be broken
# Some initialization can't take place here until this bug is fixed:
# - alias_method_chain in rails/routes.rb
initializer "devise.add_to_load_path", :after => :set_autoload_paths do |app|
load_paths.each do |path|
$LOAD_PATH << path
require "active_support/dependencies"
ActiveSupport::Dependencies.load_paths << path
unless app.config.reload_plugins
ActiveSupport::Dependencies.load_once_paths << path
end
end
end
initializer "devise.add_view_paths", :after => :initialize_framework_views do
views = "#{DEVISE_PATH}/app/views"
ActionController::Base.view_paths.concat([views]) if defined? ActionController
ActionMailer::Base.view_paths.concat([views]) if defined? ActionMailer
end
initializer "devise.load_routes_and_warden_compat" do |app|
require 'devise/rails/routes'
require 'devise/rails/warden_compat'
end
initializer "devise.add_middleware", :before => :build_middleware_stack do |app|
# Adds Warden Manager to Rails middleware stack, configuring default devise
# strategy and also the failure app.
app.config.middleware.use Warden::Manager do |config|
Devise.configure_warden(config)
end
end
initializer "devise.after_initialize", :after => :after_initialize do |app|
# TODO: this needs to be done in the user's configuration
# until initializer dependencies work properly
#require "devise/orm/#{Devise.orm}"
I18n.load_path.unshift File.expand_path(File.join(File.dirname(__FILE__), 'locales', 'en.yml'))
end
end
end
|
require 'rails_helper'
describe 'pages/new' do
before:each do
assign(:page, Page.new(
title: 'MyString'
))
end
it 'renders new page form' do
render
assert_select 'form[action=?][method=?]', pages_path, 'post' do
assert_select 'input[name=?]', 'page[title]'
assert_select 'textarea[name=?]', 'page[content]'
end
end
end
|
class IndividualsController < ApplicationController
before_action :authenticate_user!
before_action :set_individual, only: [:show, :edit, :update, :destroy]
def index
# @individuals = Individual.all
respond_to do |format|
format.html
format.json { render json: IndividualDatatable.new(params) }
end
end
def show
end
def new
@individual = Individual.new
end
def create
@individual = Individual.new(individual_params)
if @individual.save
redirect_to individuals_path
else
render :new
end
end
def edit
end
def update
if @individual.update_attributes(individual_params)
redirect_to individuals_path, suссess: 'Сотрудник успешно обновлен'
else
flash.now[:danger] = 'Сотрудник не обновлен'
render :edit
end
end
def destroy
@individual.destroy
redirect_to individuals_path, suссess: 'Сотрудник успешно удален'
end
private
def individual_params
params.require(:individual).permit(:full_name,:last_name,:first_name,:middle_name)
end
def set_individual
@individual = Individual.find(params[:id])
end
end
|
# -*- encoding: utf-8 -*-
require 'eventbus/common_init'
# This is taken almost directly from the Stomp gem's example
# logger, with minor modifications. Will work on customizing later.
# == Example STOMP call back logger class.
#
# Optional callback methods:
#
# * on_connecting: connection starting
# * on_connected: successful connect
# * on_connectfail: unsuccessful connect (will usually be retried)
# * on_disconnect: successful disconnect
#
# * on_miscerr: on miscellaneous xmit/recv errors
#
# * on_publish: publish called
# * on_subscribe: subscribe called
# * on_unsubscribe: unsubscribe called
#
# * on_begin: begin called
# * on_ack: ack called
# * on_nack: nack called
# * on_commit: commit called
# * on_abort: abort called
#
# * on_receive: receive called and successful
#
# * on_ssl_connecting: SSL connection starting
# * on_ssl_connected: successful SSL connect
# * on_ssl_connectfail: unsuccessful SSL connect (will usually be retried)
#
# * on_hbread_fail: unsuccessful Heartbeat read
# * on_hbwrite_fail: unsuccessful Heartbeat write
# * on_hbfire: on any send or receive heartbeat
#
# All methods are optional, at the user's requirements.
#
# If a method is not provided, it is not called (of course.)
#
# IMPORTANT NOTE: in general, call back logging methods *SHOULD* not raise exceptions,
# otherwise the underlying STOMP connection may fail in mysterious ways.
#
# There are two useful exceptions to this rule for:
#
# * on_connectfail
# * on_ssl_connectfail
#
# These two methods can raise a Stomp::Errors::LoggerConnectionError. If this
# exception is raised, it is passed up the chain to the caller.
#
# Callback parameters: are a copy of the @parameters instance variable for
# the Stomp::Connection.
#
module EventBus
module Connectors
module Stomp
class Slogger
# Initialize a new callback logger instance.
def initialize(init_parms = nil)
EventBus.logger.info("Logger is: #{EventBus.logger.inspect}")
EventBus.logger.info("Logger initialization complete.")
end
# Log connecting events
def on_connecting(parms)
begin
EventBus.logger.info "Connecting: #{info(parms)}"
rescue
EventBus.logger.debug "Connecting oops"
end
end
# Log connected events
def on_connected(parms)
begin
EventBus.logger.info "Connected: #{info(parms)}"
rescue
EventBus.logger.debug "Connected oops"
end
end
# Log connectfail events
def on_connectfail(parms)
begin
EventBus.logger.error "Connect Fail #{info(parms)}"
rescue
EventBus.logger.debug "Connect Fail oops"
end
=begin
# An example LoggerConnectionError raise
EventBus.logger.debug "Connect Fail, will raise"
raise Stomp::Error::LoggerConnectionError.new("quit from connect fail")
=end
end
# Log disconnect events
def on_disconnect(parms)
begin
EventBus.logger.info "Disconnected #{info(parms)}"
rescue
EventBus.logger.debug "Disconnected oops"
end
end
# Log miscellaneous errors
def on_miscerr(parms, errstr)
begin
EventBus.logger.unknown "Miscellaneous Error #{info(parms)}"
EventBus.logger.unknown "Miscellaneous Error String #{errstr}"
rescue
EventBus.logger.debug "Miscellaneous Error oops"
end
end
# Log Subscribe
def on_subscribe(parms, headers)
begin
EventBus.logger.info "Subscribe Parms #{info(parms)}"
EventBus.logger.info "Subscribe Headers #{headers}"
rescue
EventBus.logger.debug "Subscribe oops"
end
end
# Log UnSubscribe
def on_unsubscribe(parms, headers)
begin
EventBus.logger.info "UnSubscribe Parms #{info(parms)}"
EventBus.logger.info "UnSubscribe Headers #{headers}"
rescue
EventBus.logger.debug "UnSubscribe oops"
end
end
# Log Publish
def on_publish(parms, message, headers)
begin
EventBus.logger.info "Publish Parms #{info(parms)}"
EventBus.logger.info "Publish Message #{message}"
EventBus.logger.info "Publish Headers #{headers}"
rescue
EventBus.logger.debug "Publish oops"
end
end
# Log Receive
def on_receive(parms, result)
begin
EventBus.logger.info "Receive Parms #{info(parms)}"
EventBus.logger.info "Receive Result #{result}"
rescue
EventBus.logger.debug "Receive oops"
end
end
# Log Begin
def on_begin(parms, headers)
begin
EventBus.logger.info "Begin Parms #{info(parms)}"
EventBus.logger.info "Begin Result #{headers}"
rescue
EventBus.logger.debug "Begin oops"
end
end
# Log Ack
def on_ack(parms, headers)
begin
EventBus.logger.debug "Ack Parms #{info(parms)}"
EventBus.logger.debug "Ack Result #{headers}"
rescue
EventBus.logger.debug "Ack oops"
end
end
# Log NAck
def on_nack(parms, headers)
begin
EventBus.logger.debug "NAck Parms #{info(parms)}"
EventBus.logger.debug "NAck Result #{headers}"
rescue
EventBus.logger.debug "NAck oops"
end
end
# Log Commit
def on_commit(parms, headers)
begin
EventBus.logger.info "Commit Parms #{info(parms)}"
EventBus.logger.info "Commit Result #{headers}"
rescue
EventBus.logger.debug "Commit oops"
end
end
# Log Abort
def on_abort(parms, headers)
begin
EventBus.logger.info "Abort Parms #{info(parms)}"
EventBus.logger.info "Abort Result #{headers}"
rescue
EventBus.logger.debug "Abort oops"
end
end
# Stomp 1.1+ - heart beat read (receive) failed.
def on_hbread_fail(parms, ticker_data)
begin
EventBus.logger.warn "Hbreadf Parms #{info(parms)}"
EventBus.logger.warn "Hbreadf Result #{ticker_data.inspect}"
rescue
EventBus.logger.debug "Hbreadf oops"
end
end
# Stomp 1.1+ - heart beat send (transmit) failed.
def on_hbwrite_fail(parms, ticker_data)
begin
EventBus.logger.warn "Hbwritef Parms #{info(parms)}"
EventBus.logger.warn "Hbwritef Result #{ticker_data.inspect}"
rescue
EventBus.logger.debug "Hbwritef oops"
end
end
# Log SSL connection start.
def on_ssl_connecting(parms)
begin
EventBus.logger.info "SSL Connecting Parms #{info(parms)}"
rescue
EventBus.logger.debug "SSL Connecting oops"
end
end
# Log a successful SSL connect.
def on_ssl_connected(parms)
begin
EventBus.logger.info "SSL Connected Parms #{info(parms)}"
rescue
EventBus.logger.debug "SSL Connected oops"
end
end
# Log an unsuccessful SSL connect.
def on_ssl_connectfail(parms)
begin
EventBus.logger.error "SSL Connect Fail Parms #{info(parms)}"
EventBus.logger.error "SSL Connect Fail Exception #{parms[:ssl_exception]}, #{parms[:ssl_exception].message}"
rescue
EventBus.logger.debug "SSL Connect Fail oops"
end
=begin
# An example LoggerConnectionError raise
EventBus.logger.debug "SSL Connect Fail, will raise"
raise Stomp::Error::LoggerConnectionError.new("quit from SSL connect")
=end
end
# Log heart beat fires
def on_hbfire(parms, srind, curt)
begin
EventBus.logger.debug "HeartBeat Fire Parms #{info(parms)}"
EventBus.logger.debug "HeartBeat Fire Send/Receive #{srind}"
rescue
EventBus.logger.debug "HeartBeat Fire oops"
end
end
private
# Example information extract.
def info(parms)
#
# Available in the parms Hash:
# parms[:cur_host]
# parms[:cur_port]
# parms[:cur_login]
# parms[:cur_passcode]
# parms[:cur_ssl]
# parms[:cur_recondelay]
# parms[:cur_parseto]
# parms[:cur_conattempts]
# parms[:openstat]
#
# For the on_ssl_connectfail callback these are also available:
# parms[:ssl_exception]
#
"Host: #{parms[:cur_host]}, Port: #{parms[:cur_port]}, Login: #{parms[:cur_login]}, Passcode: #{parms[:cur_passcode]}," +
" ssl: #{parms[:cur_ssl]}, open: #{parms[:openstat]}"
end
end
# module ends
end
end
end |
json.array!(@tokens) do |token|
json.extract! token, :id, :status, :comment, :user_id
json.url token_url(token, format: :json)
end
|
name 'instana-agent'
maintainer 'INSTANA Inc'
maintainer_email 'stefan.staudenmeyer@instana.com'
license 'Proprietary - All Rights Reserved'
description 'Installs/Configures instana-agent'
long_description IO.read(File.join(File.dirname(__FILE__), 'README.md'))
version '0.1.0'
provides 'instana-agent::default'
provides 'instana-agent::check_java'
provides 'instana-agent::download'
provides 'instana-agent::install'
provides 'instana-agent::run'
recipe 'default', 'Check the java installation, download and start the agent'
recipe 'check_java', 'Check the java installation, JDK and Version'
recipe 'download', 'Download the instana agent'
recipe 'install', 'Unzips the instana agent to a specified location'
recipe 'run', 'Runs the instana agent'
|
class AddPickupAndDropoffToPassengers < ActiveRecord::Migration
def self.up
add_column :passengers, :pickup_at, :datetime
add_column :passengers, :dropoff_at, :datetime
end
def self.down
remove_column :passengers, :dropoff_at
remove_column :passengers, :pickup_at
end
end
|
class AddRestaurantIdToSpecial < ActiveRecord::Migration
def change
add_column :specials, :restaurant_id, :integer
end
end
|
module RemoteStorage
module BackendInterface
class NotImplemented < Exception ; end
def get_auth_token(user, password)
$stderr.puts "WARNING: get_auth_token() always returns 'fake-token'"
return 'fake-token'
end
def authorize_request(user, category, token)
$stderr.puts "WARNING: authorize_request() always returns true"
return true
end
%w(get put delete).each do |verb|
method_name = "#{verb}_data"
define_method(method_name) { |*_|
raise NotImplemented, method_name
}
end
def check_categories(user, *categories)
categories.map do |category|
{
:name => category,
:exists => category_exists?(user, category)
}
end
end
def category_exists?(user, category)
true
end
end
end
|
class Api::TagsController < ApplicationController
before_action :require_logged_in
before_action :proper_ownership, only: [:show, :update, :destroy]
def index
@tags = Tag.where(user_id: current_user.id)
end
def show
@tag = Tag.find(params[:id])
end
def create
@tag = Tag.new(tag_params)
@tag.user_id = current_user.id
if @tag.save
if params[:note_id]
Tagging.create(note_id: params[:note_id], tag_id: @tag.id)
end
render :show
else
render json: @tag.errors.full_messages, status: 422
end
end
def update
@tag = Tag.find(params[:id])
if @tag.update(tag_params)
render :show
else
render json: @tag.errors.full_messages, status: 422
end
end
def destroy
@tag = Tag.find(params[:id])
@tag.destroy
render :show
end
def add_tagging
@tagging = Tagging.new(tagging_params)
if @tagging.save
@tags = Tag.where(user_id: current_user.id)
@tag_message = ['Tag Added']
render :tagging
else
render json: @tagging.errors.full_messages, status: 422
end
end
def remove_tagging
@tagging = Tagging.find_by(note_id: tagging_params[:note_id], tag_id: tagging_params[:tag_id])
if @tagging.destroy
@tags = Tag.where(user_id: current_user.id)
@tag_message = ['TagRemoved']
render :tagging
else
render json: @tagging.errors.full_messages, status: 422
end
end
private
def tag_params
params.require(:tag).permit(:label, :user_id)
end
def tagging_params
params.require(:tagging).permit(:tag_id, :note_id)
end
def owns_tag?(tag)
current_user.id == tag.user_id
end
def proper_ownership
unless owns_tag?(Tag.find(params[:id]))
render json: ['Permission denied: you do not own these tags'], status: 401
end
end
end
|
module API
module Spotify
WS_URL = "https://api.spotify.com/v1"
PERMITTED_TYPES = %w{album artist track}
URI_REGEX = /spotify:([a-z]+):(\w+)/
def search(query)
# Check that parameters are correct or return the corresponding error
query = query.gsub('!ssearch', '').strip
type, q = query.split(' ')
return "Invalid search request. You have to provide a valid type (artist, album or track) and then your query" if type.nil? || q.nil?
return "Bad request. Allowed types are album, artist and track." unless PERMITTED_TYPES.include?(type)
# Perform the search and return the result
result = ""
response = HTTParty.get("#{WS_URL}/search?type=#{type}&q=#{URI.encode(q)}")
if response["#{type}s"] && response["#{type}s"]['items'].count > 0
i = 1
response["#{type}s"]['items'].each do |item|
result += "#{i}. #{item['name']} --> #{item['uri']} --> #{item['external_urls']['spotify']}\n"
i += 1
break if i == 5
end
else
result = "Nothing found with that parameter."
end
result
end
def parse_uri(uri)
matcher = uri.match(URI_REGEX)
type = matcher[1]
spotify_id = matcher[2]
parsed_uri = nil
response = HTTParty.get("#{WS_URL}/#{type}s/#{spotify_id}?client_id=#{@@client_id}")
if response['name']
if response['artists']
parsed_uri = response['artists'][0]['name'] + " - " + response['name']
else
parsed_uri = response['name']
end
end
parsed_uri
end
end
end |
cars = 100 #Assigns the variable "cars" with the number 100
space_in_a_car = 4.0 #Assigns the variable "space_in_a_car" the number 4.0
drivers = 30 #Assigns the variable "drivers" the number 30
passengers = 90 #Assigns the variable "passengers" the number 90
cars_not_driven = cars - drivers #Assigns the variable "cars_not_driven" the value of "cars" - "drivers" or 70
cars_driven = drivers #Assigns the variable "cars_driven" the value of "drivers"
carpool_capacity = cars_driven * space_in_a_car #Assigns the variable "carpool_capacity" the value of cars_driven * space_in_a_car
average_passengers_per_car = passengers / cars_driven #Assigns the variable "average_passengers_per_car" the value passengers / cars_driven
puts "There are #{cars} cars available."
puts "There are only #{drivers} drivers available"
puts "There will be #{cars_not_driven} empty"
puts "We can transport #{carpool_capacity} people"
puts "We have #{passengers} to carpool today."
puts "We need to put about #{average_passengers_per_car} in each car."
|
class AddApplicationToAppStatus < ActiveRecord::Migration
def change
add_reference :app_statuses, :student_application, index: true
add_foreign_key :app_statuses, :student_applications
end
end
|
require 'osc'
module Cosy
# TODO: rather than use this artificially imposed class hierarchy
# it would be cleaner to use the "Chain of Responsibility" pattern
# and make this one handler that can be chained up to handel events
class AbstractOscRenderer < AbstractRenderer
def initialize(options={})
super
@clients = {}
if @timeline
@timeline.find_all{|event| event.is_a? Event::OscMessage}.each do |osc_message|
# Open all the connections we'll need now
get_client osc_message
end
end
end
##########
private
def get_client(osc_message)
host, port = osc_message.host, osc_message.port
client = @clients[[host,port]]
if not client
client = OSC::SimpleClient.new(host,port)
@clients[[host,port]] = client
end
return client
end
def osc(osc_message)
client = get_client osc_message
msg = OSC::Message.new(osc_message.path, nil, *osc_message.args)
begin
client.send(msg)
rescue => exception
STDERR.puts "OSC message failed to send: #{osc_message}"
STDERR.puts "#{exception.message}"
end
end
end
end
|
module V1
class AuthAPI < Base
resource :auth do
desc "Creates and returns access_token if valid signin"
params do
requires :email, type: String, desc: "Email address"
requires :password, type: String, desc: "Password"
end
post :signin do
user = User.where(email: params[:email]).first
if user && user.valid_password?(params[:password])
key = ApiKey.create(user_id: user.id)
{token: key.access_token}
else
error!('Unauthorized.', 401)
end
end
desc "Returns pong if authenticated correctly"
# params do
# requires :token, type: String, desc: "Access token."
# end
get :ping do
authenticate!
{ message: "pong" }
end
end
end
end |
class User < ActiveRecord::Base
# :token_authenticatable, :confirmable,
# :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
devise :omniauthable
# Setup accessible (or protected) attributes for your model
attr_accessible :username, :password, :password_confirmation, :remember_me, :login, :fee
# attr_accessible :title, :body
attr_accessor :login
has_many :rss_providers
has_many :user_twitters
def self.find_first_by_auth_conditions(warden_conditions)
conditions = warden_conditions.dup
if login = conditions.delete(:login)
where(conditions).where(["lower(username) = :value OR lower(email) = :value", { :value => login.downcase }]).first
else
where(conditions).first
end
end
def valid_password?(password)
!provider.nil? || super(password)
end
def email_required?
false
end
def max_twitt
if self.fee == 2
13
elsif self.fee == 1
6
else
2
end
end
def max_retwitt
if self.fee == 2
51
elsif self.fee == 1
11
else
0
end
end
def can_add_account
if self.fee == 2
true
elsif self.fee == 1
self.user_twitters.count < 3
else
false
end
end
def can_add_rss_provider
if self.fee == 2
true
elsif self.fee == 1
self.rss_providers.count < 5
else
false
end
end
end
|
class QuotaPlan < Plan
attr_accessible :quota
# Hack to calculate the optimal price. We will retire quota plan soon
def self.price quota
plan100 = quota / 50
plan50 = (quota % 50) / 20
plan100 * 100 + plan50 * 50
end
def self.customize price, quota, name=""
name = "#{quota} credits plan" if name.empty?
QuotaPlan.find_or_create_by_price_and_quota_and_name(price, quota, name)
end
end |
class Api::V2::MatchesController < ApplicationController
before_action :load_table
before_action :authorize_ongoing_match, only: :setup
after_action :update_match_channel, except: :show
def ongoing
match = @table.ongoing_match
authorize! :read, match
render_match(match)
end
# FIXME: This action destroys the match on the specified table, but currently
# makes a new one on the default table. Because being "active" is currently
# not table specific, this is fine for now.
def setup
ongoing_match = @table.ongoing_match
authorize! :destroy, ongoing_match
if ongoing_match.present? && !ongoing_match.destroy
render :show, status: :unprocessable_entity
return
end
render_match(
Match.setup!,
success_status: :created,
failure_status: :unprocessable_entity
)
end
private
def load_table
@table = Table.find(params[:table_id])
authorize! :read, @table
rescue ActiveRecord::RecordNotFound
render json: nil, status: :not_found
end
def authorize_ongoing_match
authorize! :update, ongoing_match
end
def render_match(match, success_status: :ok, failure_status: :not_found)
unless match
render json: nil, status: failure_status
return
end
render(
json: match,
serializer: OngoingMatchSerializer,
include: [
:home_player,
:away_player,
:next_matchup,
:betting_info
],
status: success_status
)
end
end
|
require 'sinatra'
require 'dotenv/load'
require 'airrecord'
require 'pry'
require 'haml'
set :protection, :except => :frame_options
set :bind, '0.0.0.0'
# When browser requests default page for domain, the path is '/'
# The most basic thing to do is return a string of HTML that the browser will display
get '/' do
"<html><body><h1>Home Page</h1></body></html>"
end
# Ruby has lots of ways to make strings with variables interpolated into the string.
# ( FYI These are basic examples and for production apps you have to consider attack vectors)
get '/p1' do
firstname = "John"
lastname = "Doe"
# This funny contruct in Ruby is called a HEREDDOC and lets you crerate multi-line strings easily
html = <<-HTML
<html>
<body>
Name: #{firstname} #{lastname}
</body>
</html>
HTML
end
# Typically you will use HTML template languages to generate the HTML easier (like ERB/HAML/Slim)
get '/p2' do
states = ['Cali', 'Nevada', 'Texas']
html = <<-HTML
<html>
<body>
<ul>
<% states.each do |s| %>
<li><%= s %></li>
<% end %>
</body>
</html>
HTML
erb html, locals: {states: states}
end
# You usually split out templates into their own .html files, and just references them here in the code.
get '/mytemplate' do
erb :index, locals: { host: request.host }
# Ruby lets you do a lot of shortcuts to save typing and make things look nicer.
# The above line can also be written as
# erb(:index, {locals: {host: request.host}})
# Or using the old Hash syntax ( the => is called a Hash rocket). Largely replaced by the new syntax which makes it look more like JSON/Javascript
# erb(:index, {:locals => {:host => request.host}})
end
# Ruby web frameworks like Sinatra and Rails use Rack to handle the HTTP part of things. Rack expects an array of 3 elements, HTTP response code, a hash of HTTP headers, and a string of the content to return. Typically you dont need to know this, as the frameworks handle it all for you.
get '/lowlevelbaby' do
[200, {}, "Low Level"]
# You could also say
# return [200, {}, "Low Level"]
# But Ruby *always* returns the last thing to run, so you dont have to explicitly say it
end
# Show whats in the ENV var. Of course, NEVER DO THIS IN PROD! It will expose all your secrets :)
get '/env' do
ENV.inspect
end
#
# AirTable Integration
#
Airrecord.api_key = ENV['AIRTABLE_API_KEY']
class SurfLocation < Airrecord::Table
self.base_key = ENV['AIRTABLE_BASE_ID']
self.table_name = "SurfLocations"
end
get '/surf_locations' do
erb :surf_locations, {locals: {surf_locations: SurfLocation.all}}
end
get '/surf_locations_haml' do
haml :surf_locations, {locals: {surf_locations: SurfLocation.all}}
end
get '/surf_locations_with_layout' do
erb :surf_locations_with_layout, {layout: :application_layout, locals: {surf_locations: SurfLocation.all}}
end
get '/surf_locations/:id' do
surf_location = SurfLocation.find(params['id'])
erb :surf_location, {locals: {surf_location: surf_location}}
end
post '/surf_locations/search' do
# One way is to grab all records from Airtable, then filter them here in Ruby. This could be bad if there
# are a lot of records, and maybe should tell Airtable to filter them.
# This will find exact matches on name
locs = SurfLocation.all.filter{|loc| params["query"] == loc["Name"] }
# This one uses regular expressions to find all matches
#locs = SurfLocation.all.filter{|loc| /#{params["query"]}/i =~ loc["Name"] }
erb :_search_results, {locals: {search_results: locs}}
end
get '/debug' do
binding.pry
end |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.