text stringlengths 10 2.61M |
|---|
class Api::CountriesController < ApplicationController
before_action :set_country, only: [:show]
def index
@countries = Country.all
json_response(@countries)
end
end
|
class ProjectsController < ApplicationController
before_action :private_access
before_action :paid_access
# GET /subjects/:subject_id/projects/:id
def show
@project = Project.find(params[:id])
@project_solution = @project.project_solutions.find_or_initialize_by(user_id: current_user.id)
@project.subject
end
end
|
class Series < ApplicationRecord
has_and_belongs_to_many :actors
has_many :reviews
has_and_belongs_to_many :locations
end
|
class AddAutoincrementToQuantityColumn < ActiveRecord::Migration
def change
change_column :products, :quantity, :integer, default: 1
end
end
|
CraigslistJr::Application.routes.draw do
root to: 'posts#index'
resources :posts
resources :categories, :only => :index
end
|
class RemoveCongressHouseIdColumns < ActiveRecord::Migration
def change
remove_column :bills, :congress_house_id, :integer
remove_column :legislators, :congress_house_id, :integer
change_table :bills do |t|
t.belongs_to :chamber
end
change_table :legislators do |t|
t.belongs_to :chamber
end
end
end
|
When (/^I made long tap on map$/) {
map_selector = "view:'MKMapView'"
tap_and_hold(map_selector)
}
Then (/^I see a bookmark pin added$/) {
pin_selector = "view:'MKPinAnnotationView' marked:'Unnamed'"
wait_for_element_to_exist(pin_selector)
}
When (/^I touch a pin$/) {
pin_selector = "view:'_MKSmallCalloutPassthroughButton'"
wait_for_element_to_exist(pin_selector)
touch(pin_selector)
}
|
module Aucklandia
module VehiclePositions
VEHICLE_POSITIONS_ENDPOINT = '/public/realtime/vehiclelocations'
def get_vehicle_positions(trip_id: nil, vehicle_id: nil)
params = { tripid: trip_id, vehicleid: vehicle_id }.delete_if { |k,v| v.nil? }
url = build_url(BASE_URL, VEHICLE_POSITIONS_ENDPOINT, params: params)
response = get(url)
JSON.parse(response)['response']['entity']
end
def get_vehicle_position_by_vehicle_id(vehicle_id)
get_vehicle_positions(vehicle_id: vehicle_id).first
end
def get_vehicle_positions_by_route_id(route_id)
get_vehicle_positions.select do |vehicle_position|
vehicle_position if vehicle_position['vehicle']['trip']['route_id'] == route_id
end
end
end
end |
module Chart
# ---------burndown chart methods----------
def start_end_date_array
# group的第一天到最後一天
(start_date.to_date..end_date.to_date).map {|date| date.strftime("%m/%d")}
end
# 回傳對應日期的加總point陣列
def point_array
(start_date.to_date..end_date.to_date).map {|date| count_date_point(date)}
end
# 實際完成的line: 帶入特定日期,就會把在那個日期之前完成的item找到並加總point
def count_date_point(date)
# 每天的point總和:還沒完成的item的point加起來
sum_point = 0
items.each do |item|
sum_point += item.point if item.finish_date.nil? || item.finish_date > date
end
return sum_point
end
# 理想的line
def avg_point_array
total_day = (end_date.to_date - start_date.to_date).to_i
avg_day_point = total_point / total_day
# 每天減一份平均值,減到只剩0為止
total_point.step(0 ,-avg_day_point).to_a
end
def total_point
items.inject(0){|sum, item| sum + item.point}
end
# ---------pie chart methods----------
def find_all_members_name
board.workspace.all_members.map(&:display_name)
end
def find_all_members_id
board.workspace.all_members.map(&:id)
end
def find_all_members_point_array
# 把member_id當參數, 傳進另一個item的class method
find_all_members_id.map{ |member_id| items.get_point_by_user_id(member_id)}
end
# ---------bar chart methods----------
def find_items_array
items.map(&:name)
end
def find_items_expected_spend_day_array
items.map(&:expected_spend_day)
end
def find_items_actual_spend_day_array
items.map(&:actual_spend_day)
end
end |
# frozen_string_literal: true
require 'controller_test'
class SurveysControllerTest < ActionController::TestCase
setup do
@survey = surveys(:first_survey)
login(:uwe)
end
test 'should get index' do
get :index
assert_response :success
end
test 'should get new' do
get :new
assert_response :success
end
test 'should create survey' do
assert_difference('Survey.count') do
post :create, params: { survey: {
category: @survey.category,
expires_at: @survey.expires_at,
footer: @survey.footer,
group_id: @survey.group_id,
header: @survey.header,
position: @survey.position,
title: @survey.title,
} }
end
assert_redirected_to survey_path(Survey.last)
end
test 'should show survey' do
get :show, params: { id: @survey }
assert_response :success
end
test 'should get edit' do
get :edit, params: { id: @survey }
assert_response :success
end
test 'should update survey' do
patch :update, params: { id: @survey, survey: {
category: @survey.category,
expires_at: @survey.expires_at,
footer: @survey.footer,
group_id: @survey.group_id,
header: @survey.header,
position: @survey.position,
title: @survey.title,
} }
assert_redirected_to survey_path(@survey)
end
test 'should destroy survey' do
assert_difference('Survey.count', -1) do
delete :destroy, params: { id: @survey }
end
assert_redirected_to surveys_path
end
end
|
class ChromeLogger
class Console
attr_reader :log_items
def self.logger_for( *kinds )
kinds.each do | kind |
class_eval <<-___
def #{ kind }( *args )
add_log_items '#{ kind }' , *args
end
___
end
end
def initialize
@log_items = []
end
def add_log_items( level , *args )
backtrace = caller[ 1 ] # 2 up!
item = [ args , backtrace , level ]
@log_items << item
end
def data
{
'version' => ChromeLogger::VERSION,
'columns' => [ 'log' , 'backtrace' , 'type' ],
'rows' => log_items
}
end
logger_for \
:error,
:group,
:groupCollapsed,
:groupEnd,
:info,
:warn
alias_method :group_collapsed , :groupCollapsed
alias_method :group_end , :groupEnd
# custom to let chrome plugin decide default
def log( *args )
add_log_items '' , *args
end
end
end
|
class AddUserToTransactions < ActiveRecord::Migration[6.1]
def change
add_reference :transactions, :user, null: false,
foreign_key: true,
type: :uuid
end
end
|
class Admin::ProductReviewsController < ApplicationController
before_filter :require_admin
def index
@store = current_store
@product = Product.find(params[:product_id])
@featured_comments = @product.featured_comments
@nonfeatured_comments = @product.nonfeatured_comments
end
def update
@product = Product.find(params[:product_id])
@product_review = ProductReview.find(params[:id])
if @product_review.update_attributes(featured: params[:featured])
redirect_to store_admin_product_reviews_path(current_store, @product.id),
notice: 'Successfully Updated Product Review Featured Status'
else
render :index,
notice: 'Failed to update Product Review Featured Status'
end
end
end
|
require 'rails_helper'
describe "Cats", type: :request do
it "gets a list of Cats" do
# Create a new cat in the Test Database (this is not the same one as development)
Cat.create(name: 'Felix', age: 2, enjoys: 'Walks in the park', story: 'story', image: 'image')
# Make a request to the API
get '/cats'
# Convert the response into a Ruby Hash
json = JSON.parse(response.body)
# Assure that we got a successful response
expect(response).to have_http_status(:ok)
# Assure that we got one result back as expected
expect(json.length).to eq 1
end
it "creates a cat" do
# The params we are going to send with the request
cat_params = {
cat: {
name: 'Buster',
age: 4,
enjoys: 'Meow Mix, and plenty of sunshine.',
story: 'Loves to eat. Hates cucumbers.',
image: 'image of Buster'
}
}
# Send the request to the server
post '/cats', params: cat_params
# Assure that we get a success back
expect(response).to have_http_status(:ok)
# Look up the cat we expect to be created in the Database
cat = Cat.first
# Assure that the created cat has the correct attributes
expect(cat.name).to eq 'Buster'
end
it "doesn't create a cat without a name" do
cat_params = {
cat: {
age: 2,
enjoys: 'Walks',
story: 'things',
image: 'picture'
}
}
# Send the request to the server
post '/cats', params: cat_params
# expect an error if the cat_params does not have a name
expect(response.status).to eq 422
# Convert the JSON response into a Ruby Hash
cats = JSON.parse(response.body)
# Errors are returned as an array because there could be more than one, if there are more than one validation failures on an attribute.
# NOTE: The string that follows .include is NOT arbitrary
expect(cats['name']).to include "can't be blank"
end
it "doesn't create a cat that has an enjoys category with less than 10 characters" do
cat_params = {
cat: {
name:'Benedict',
age: 2,
enjoys: 'Walks',
story: 'things',
image: 'picture'
}
}
# Send the request to the server
post '/cats', params: cat_params
# expect an error if the enjoys is not 10 characters at least
expect(response.status).to eq 422
# Convert the JSON response into a Ruby Hash
cats = JSON.parse(response.body)
# Errors are returned as an array because there could be more than one, if there are more than one validation failures on an attribute.
# NOTE: The string that follows .include is NOT arbitrary
expect(cats['enjoys']).to include "is too short (minimum is 10 characters)"
end
end
|
require 'rails_helper'
RSpec.describe UsersController, type: :controller do
let(:valid_attributes) {{
first_name: 'joe',
last_name: 'smoe',
email: 'joe.smoe@example.com',
encrypted_password: 'asdasdjh32kjhr23fdsf',
password: 'password',
confirmation_token: nil,
remember_token: '0fa4c7fa1aec8d358b64d857d6d6e6e1492aca3e'
}}
let(:invalid_attributes) {{
first_name: 'karen',
last_name: 'duds',
age: '27'
}}
let(:valid_session) { {} }
describe "GET #new" do
it "assigns a new user as @user" do
get :new, {}, valid_session
expect(assigns(:user)).to be_a_new(User)
end
end
describe "POST #create" do
context "with valid params" do
it "creates a new User" do
expect {
post :create, {:user => valid_attributes}, valid_session
}.to change(User, :count).by(1)
end
it "assigns a newly created user as @user" do
post :create, {:user => valid_attributes}, valid_session
expect(assigns(:user)).to be_a(User)
expect(assigns(:user)).to be_persisted
end
it "sets the users credit limit to $1000" do
post :create, {:user => valid_attributes}, valid_session
expect(assigns(:user).credit_limit).to eq(Money.new(100000, 'USD'))
end
it "redirects to the root_path" do
post :create, {:user => valid_attributes}, valid_session
expect(response).to redirect_to(root_path)
end
end
context "with invalid params" do
it "assigns a newly created but unsaved user as @user" do
post :create, {:user => invalid_attributes}, valid_session
expect(assigns(:user)).to be_a_new(User)
end
it "re-renders the 'new' template" do
post :create, {:user => invalid_attributes}, valid_session
expect(response).to render_template("new")
end
end
end
end
|
# frozen_string_literal: true
# Copyright (C) 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 Crypt
# An ExplicitEncrypter is an object that performs explicit encryption
# operations and handles all associated options and instance variables.
#
# @api private
class ExplicitEncrypter
extend Forwardable
# Create a new ExplicitEncrypter object.
#
# @param [ Mongo::Client ] key_vault_client An instance of Mongo::Client
# to connect to the key vault collection.
# @param [ String ] key_vault_namespace The namespace of the key vault
# collection in the format "db_name.collection_name".
# @param [ Crypt::KMS::Credentials ] kms_providers A hash of key management service
# configuration information.
# @param [ Hash ] kms_tls_options TLS options to connect to KMS
# providers. Keys of the hash should be KSM provider names; values
# should be hashes of TLS connection options. The options are equivalent
# to TLS connection options of Mongo::Client.
def initialize(key_vault_client, key_vault_namespace, kms_providers, kms_tls_options)
Crypt.validate_ffi!
@crypt_handle = Handle.new(
kms_providers,
kms_tls_options,
explicit_encryption_only: true
)
@encryption_io = EncryptionIO.new(
key_vault_client: key_vault_client,
metadata_client: nil,
key_vault_namespace: key_vault_namespace
)
end
# Generates a data key used for encryption/decryption and stores
# that key in the KMS collection. The generated key is encrypted with
# the KMS master key.
#
# @param [ Mongo::Crypt::KMS::MasterKeyDocument ] master_key_document The master
# key document that contains master encryption key parameters.
# @param [ Array<String> | nil ] key_alt_names An optional array of strings specifying
# alternate names for the new data key.
# @param [ String | nil ] key_material Optional 96 bytes to use as
# custom key material for the data key being created.
# If key_material option is given, the custom key material is used
# for encrypting and decrypting data.
#
# @return [ BSON::Binary ] The 16-byte UUID of the new data key as a
# BSON::Binary object with type :uuid.
def create_and_insert_data_key(master_key_document, key_alt_names, key_material = nil)
data_key_document = Crypt::DataKeyContext.new(
@crypt_handle,
@encryption_io,
master_key_document,
key_alt_names,
key_material
).run_state_machine
@encryption_io.insert_data_key(data_key_document).inserted_id
end
# Encrypts a value using the specified encryption key and algorithm
#
# @param [ Object ] value The value to encrypt
# @param [ Hash ] options
#
# @option options [ BSON::Binary ] :key_id A BSON::Binary object of type :uuid
# representing the UUID of the encryption key as it is stored in the key
# vault collection.
# @option options [ String ] :key_alt_name The alternate name for the
# encryption key.
# @option options [ String ] :algorithm The algorithm used to encrypt the value.
# Valid algorithms are "AEAD_AES_256_CBC_HMAC_SHA_512-Deterministic",
# "AEAD_AES_256_CBC_HMAC_SHA_512-Random", "Indexed", "Unindexed".
# @option options [ Integer | nil ] :contention_factor Contention factor
# to be applied if encryption algorithm is set to "Indexed". If not
# provided, it defaults to a value of 0. Contention factor should be set
# only if encryption algorithm is set to "Indexed".
# @option options [ String | nil ] query_type Query type to be applied
# if encryption algorithm is set to "Indexed". Query type should be set
# only if encryption algorithm is set to "Indexed". The only allowed
# value is "equality".
#
# @note The :key_id and :key_alt_name options are mutually exclusive. Only
# one is required to perform explicit encryption.
#
# @return [ BSON::Binary ] A BSON Binary object of subtype 6 (ciphertext)
# representing the encrypted value
# @raise [ ArgumentError ] if either contention_factor or query_type
# is set, and algorithm is not "Indexed".
def encrypt(value, options)
Crypt::ExplicitEncryptionContext.new(
@crypt_handle,
@encryption_io,
{ v: value },
options
).run_state_machine['v']
end
# Encrypts a Match Expression or Aggregate Expression to query a range index.
#
# @example Encrypt Match Expression.
# encryption.encrypt_expression(
# {'$and' => [{'field' => {'$gt' => 10}}, {'field' => {'$lt' => 20 }}]}
# )
# @example Encrypt Aggregate Expression.
# encryption.encrypt_expression(
# {'$and' => [{'$gt' => ['$field', 10]}, {'$lt' => ['$field', 20]}}
# )
# {$and: [{$gt: [<fieldpath>, <value1>]}, {$lt: [<fieldpath>, <value2>]}]
# Only supported when queryType is "rangePreview" and algorithm is "RangePreview".
# @note: The Range algorithm is experimental only. It is not intended
# for public use. It is subject to breaking changes.
#
# @param [ Hash ] expression Expression to encrypt.
# # @param [ Hash ] options
# @option options [ BSON::Binary ] :key_id A BSON::Binary object of type :uuid
# representing the UUID of the encryption key as it is stored in the key
# vault collection.
# @option options [ String ] :key_alt_name The alternate name for the
# encryption key.
# @option options [ String ] :algorithm The algorithm used to encrypt the
# expression. The only allowed value is "RangePreview"
# @option options [ Integer | nil ] :contention_factor Contention factor
# to be applied If not provided, it defaults to a value of 0.
# @option options [ String | nil ] query_type Query type to be applied.
# The only allowed value is "rangePreview".
# @option options [ Hash | nil ] :range_opts Specifies index options for
# a Queryable Encryption field supporting "rangePreview" queries.
# Allowed options are:
# - :min
# - :max
# - :sparsity
# - :precision
# min, max, sparsity, and range must match the values set in
# the encryptedFields of the destination collection.
# For double and decimal128, min/max/precision must all be set,
# or all be unset.
#
# @note The RangePreview algorithm is experimental only. It is not
# intended for public use.
#
# @note The :key_id and :key_alt_name options are mutually exclusive. Only
# one is required to perform explicit encryption.
#
# @return [ BSON::Binary ] A BSON Binary object of subtype 6 (ciphertext)
# representing the encrypted expression.
#
# @raise [ ArgumentError ] if disallowed values in options are set.
def encrypt_expression(expression, options)
Crypt::ExplicitEncryptionExpressionContext.new(
@crypt_handle,
@encryption_io,
{ v: expression },
options
).run_state_machine['v']
end
# Decrypts a value that has already been encrypted
#
# @param [ BSON::Binary ] value A BSON Binary object of subtype 6 (ciphertext)
# that will be decrypted
#
# @return [ Object ] The decrypted value
def decrypt(value)
Crypt::ExplicitDecryptionContext.new(
@crypt_handle,
@encryption_io,
{ v: value }
).run_state_machine['v']
end
# Adds a key_alt_name for the key in the key vault collection with the given id.
#
# @param [ BSON::Binary ] id Id of the key to add new key alt name.
# @param [ String ] key_alt_name New key alt name to add.
#
# @return [ BSON::Document | nil ] Document describing the identified key
# before adding the key alt name, or nil if no such key.
def add_key_alt_name(id, key_alt_name)
@encryption_io.add_key_alt_name(id, key_alt_name)
end
# Removes the key with the given id from the key vault collection.
#
# @param [ BSON::Binary ] id Id of the key to delete.
#
# @return [ Operation::Result ] The response from the database for the delete_one
# operation that deletes the key.
def_delegators :@encryption_io, :delete_key
# Finds a single key with the given id.
#
# @param [ BSON::Binary ] id Id of the key to get.
#
# @return [ BSON::Document | nil ] The found key document or nil
# if not found.
def_delegators :@encryption_io, :get_key
# Returns a key in the key vault collection with the given key_alt_name.
#
# @param [ String ] key_alt_name Key alt name to find a key.
#
# @return [ BSON::Document | nil ] The found key document or nil
# if not found.
def_delegators :@encryption_io, :get_key_by_alt_name
# Returns all keys in the key vault collection.
#
# @return [ Collection::View ] Keys in the key vault collection.
def_delegators :@encryption_io, :get_keys
# Removes a key_alt_name from a key in the key vault collection with the given id.
#
# @param [ BSON::Binary ] id Id of the key to remove key alt name.
# @param [ String ] key_alt_name Key alt name to remove.
#
# @return [ BSON::Document | nil ] Document describing the identified key
# before removing the key alt name, or nil if no such key.
def_delegators :@encryption_io, :remove_key_alt_name
# Decrypts multiple data keys and (re-)encrypts them with a new master_key,
# or with their current master_key if a new one is not given.
#
# @param [ Hash ] filter Filter used to find keys to be updated.
# @param [ Hash ] options
#
# @option options [ String ] :provider KMS provider to encrypt keys.
# @option options [ Hash | nil ] :master_key Document describing master key
# to encrypt keys.
#
# @return [ Crypt::RewrapManyDataKeyResult ] Result of the operation.
def rewrap_many_data_key(filter, opts = {})
validate_rewrap_options!(opts)
master_key_document = master_key_for_provider(opts)
rewrap_result = Crypt::RewrapManyDataKeyContext.new(
@crypt_handle,
@encryption_io,
filter,
master_key_document
).run_state_machine
return RewrapManyDataKeyResult.new(nil) if rewrap_result.nil?
updates = updates_from_data_key_documents(rewrap_result.fetch('v'))
RewrapManyDataKeyResult.new(@encryption_io.update_data_keys(updates))
end
private
# Ensures the consistency of the options passed to #rewrap_many_data_keys.
#
# @param [ Hash ] opts the options hash to validate
#
# @raise [ ArgumentError ] if the options are not consistent or
# compatible.
def validate_rewrap_options!(opts)
return unless opts.key?(:master_key) && !opts.key?(:provider)
raise ArgumentError, 'If :master_key is specified, :provider must also be given'
end
# If a :provider is given, construct a new master key document
# with that provider.
#
# @param [ Hash ] opts the options hash
#
# @option [ String ] :provider KMS provider to encrypt keys.
#
# @return [ KMS::MasterKeyDocument | nil ] the new master key document,
# or nil if no provider was given.
def master_key_for_provider(opts)
return nil unless opts[:provider]
options = opts.dup
provider = options.delete(:provider)
KMS::MasterKeyDocument.new(provider, options)
end
# Returns the corresponding update document for each for of the given
# data key documents.
#
# @param [ Array<Hash> ] documents the data key documents
#
# @return [ Array<Hash> ] the update documents
def updates_from_data_key_documents(documents)
documents.map do |doc|
{
update_one: {
filter: { _id: doc[:_id] },
update: {
'$set' => {
masterKey: doc[:masterKey],
keyMaterial: doc[:keyMaterial]
},
'$currentDate' => { updateDate: true },
},
}
}
end
end
end
end
end
|
$:.unshift File.join(File.dirname(__FILE__), 'lib')
require 'rosette/preprocessors/break-preprocessor/version'
Gem::Specification.new do |s|
s.name = "rosette-preprocessor-break"
s.version = ::Rosette::Preprocessors::BREAK_PREPROCESSOR_VERSION
s.authors = ["Cameron Dutro"]
s.email = ["camertron@gmail.com"]
s.homepage = "http://github.com/camertron"
s.description = s.summary = "Identifies word, line, and sentence breaks in multilingual text for the Rosette internationalization platform."
s.platform = Gem::Platform::RUBY
s.has_rdoc = true
s.require_path = 'lib'
s.files = Dir["{lib,spec}/**/*", "Gemfile", "History.txt", "README.md", "Rakefile", "rosette-preprocessor-breaks.gemspec"]
end
|
class Animal
@@total_animals = 0
@@current_animals = []
attr_accessor :noise
attr_accessor :colour
def initialize(options = {})
@noise = options[:noise] || 'Grrr!'
@colour = options[:colour] || 'White'
@@total_animals += 1
@@current_animals << self # instance of Animal
end
def self.types
['Mammal','Insect','Amphibian']
end
def self.total_animals
@@total_animals
end
end |
module Cinemas
module Representers
class Relationship
attr_reader :cinema
def initialize cinema:
@cinema = cinema
end
def call
{
type: 'cinema',
id: cinema.id,
attributes: {
cinema_number: cinema.cinema_number,
total_seats: cinema.total_seats,
rows: cinema.rows,
columns: cinema.columns
}
}
end
end
end
end |
#!/usr/bin/env ruby
#--
# Copyright 2006 by Chad Fowler, Rich Kilmer, Jim Weirich and others.
# All rights reserved.
# See LICENSE.txt for permissions.
#++
require 'rubygems'
require 'rubygems/command'
module Gem
class CommandLineError < Gem::Exception; end
####################################################################
# The following mixin methods aid in the retrieving of information
# from the command line.
#
module CommandAids
# Get the single gem name from the command line. Fail if there is
# no gem name or if there is more than one gem name given.
def get_one_gem_name
args = options[:args]
if args.nil? or args.empty?
fail Gem::CommandLineError,
"Please specify a gem name on the command line (e.g. gem build GEMNAME)"
end
if args.size > 1
fail Gem::CommandLineError,
"Too many gem names (#{args.join(', ')}); please specify only one"
end
args.first
end
# Get all gem names from the command line.
def get_all_gem_names
args = options[:args]
if args.nil? or args.empty?
raise Gem::CommandLineError,
"Please specify at least one gem name (e.g. gem build GEMNAME)"
end
gem_names = args.select { |arg| arg !~ /^-/ }
end
# Get a single optional argument from the command line. If more
# than one argument is given, return only the first. Return nil if
# none are given.
def get_one_optional_argument
args = options[:args] || []
args.first
end
# True if +long+ begins with the characters from +short+.
def begins?(long, short)
return false if short.nil?
long[0, short.length] == short
end
end
####################################################################
# Mixin methods for handling the local/remote command line options.
#
module LocalRemoteOptions
# Add the local/remote options to the command line parser.
def add_local_remote_options
add_option('-l', '--local',
'Restrict operations to the LOCAL domain'
) do |value, options|
options[:domain] = :local
end
add_option('-r', '--remote',
'Restrict operations to the REMOTE domain') do
|value, options|
options[:domain] = :remote
end
add_option('-b', '--both',
'Allow LOCAL and REMOTE operations') do
|value, options|
options[:domain] = :both
end
end
# Is local fetching enabled?
def local?
options[:domain] == :local || options[:domain] == :both
end
# Is remote fetching enabled?
def remote?
options[:domain] == :remote || options[:domain] == :both
end
end
####################################################################
# Mixin methods and OptionParser options specific to the gem install
# command.
#
module InstallUpdateOptions
# Add the install/update options to the option parser.
def add_install_update_options
add_option('-i', '--install-dir DIR',
'Gem repository directory to get installed',
'gems.') do |value, options|
options[:install_dir] = File.expand_path(value)
end
add_option('-d', '--[no-]rdoc',
'Generate RDoc documentation for the gem on',
'install') do |value, options|
options[:generate_rdoc] = value
end
add_option('--[no-]ri',
'Generate RI documentation for the gem on',
'install') do |value, options|
options[:generate_ri] = value
end
add_option('-E', '--env-shebang',
"Rewrite the shebang line on installed",
"scripts to use /usr/bin/env") do |value, options|
options[:env_shebang] = value
end
add_option('-f', '--[no-]force',
'Force gem to install, bypassing dependency',
'checks') do |value, options|
options[:force] = value
end
add_option('-t', '--[no-]test',
'Run unit tests prior to installation') do
|value, options|
options[:test] = value
end
add_option('-w', '--[no-]wrappers',
'Use bin wrappers for executables',
'Not available on dosish platforms') do
|value, options|
options[:wrappers] = value
end
add_option('-P', '--trust-policy POLICY',
'Specify gem trust policy.') do
|value, options|
options[:security_policy] = value
end
add_option('--ignore-dependencies',
'Do not install any required dependent gems') do
|value, options|
options[:ignore_dependencies] = value
end
add_option('-y', '--include-dependencies',
'Unconditionally install the required',
'dependent gems') do |value, options|
options[:include_dependencies] = value
end
end
# Default options for the gem install command.
def install_update_defaults_str
'--rdoc --no-force --no-test --wrappers'
end
end
####################################################################
# Mixin methods for the version command.
#
module VersionOption
# Add the options to the option parser.
def add_version_option(taskname, *wrap)
add_option('-v', '--version VERSION',
"Specify version of gem to #{taskname}", *wrap) do
|value, options|
options[:version] = value
end
end
end
####################################################################
# Gem install command.
#
class InstallCommand < Command
include CommandAids
include VersionOption
include LocalRemoteOptions
include InstallUpdateOptions
def initialize
super(
'install',
'Install a gem into the local repository',
{
:domain => :both,
:generate_rdoc => true,
:generate_ri => true,
:force => false,
:test => false,
:wrappers => true,
:version => "> 0",
:install_dir => Gem.dir,
:security_policy => nil,
})
add_version_option('install')
add_local_remote_options
add_install_update_options
end
def usage
"#{program_name} GEMNAME [options]
or: #{program_name} GEMNAME [options] -- --build-flags"
end
def arguments
"GEMNAME name of gem to install"
end
def defaults_str
"--both --version '> 0' --rdoc --ri --no-force --no-test\n" +
"--install-dir #{Gem.dir}"
end
def execute
ENV['GEM_PATH'] = options[:install_dir]
if(options[:args].empty?)
fail Gem::CommandLineError,
"Please specify a gem name on the command line (e.g. gem build GEMNAME)"
end
options[:args].each do |gem_name|
if local?
begin
entries = []
if(File.exist?(gem_name) && !File.directory?(gem_name))
entries << gem_name
else
filepattern = gem_name + "*.gem"
entries = Dir[filepattern]
end
unless entries.size > 0
if options[:domain] == :local
alert_error "Local gem file not found: #{filepattern}"
end
else
result = Gem::Installer.new(entries.last, options).install(options[:force], options[:install_dir])
installed_gems = [result].flatten
say "Successfully installed #{installed_gems[0].name}, " +
"version #{installed_gems[0].version}" if installed_gems
end
rescue LocalInstallationError => e
say " -> Local installation can't proceed: #{e.message}"
rescue Gem::LoadError => e
say " -> Local installation can't proceed due to LoadError: #{e.message}"
rescue Gem::InstallError => e
raise "Error instaling #{gem_name}:\n\t#{e.message}"
rescue => e
# TODO: Fix this handle to allow the error to propagate to
# the top level handler. Examine the other errors as
# well. This implementation here looks suspicious to me --
# JimWeirich (4/Jan/05)
alert_error "Error installing gem #{gem_name}[.gem]: #{e.message}"
return
end
end
if remote? && installed_gems.nil?
installer = Gem::RemoteInstaller.new(options)
installed_gems = installer.install(
gem_name,
options[:version],
options[:force],
options[:install_dir])
if installed_gems
installed_gems.compact!
installed_gems.each do |spec|
say "Successfully installed #{spec.full_name}"
end
end
end
unless installed_gems
alert_error "Could not install a local " +
"or remote copy of the gem: #{gem_name}"
terminate_interaction(1)
end
# NOTE: *All* of the RI documents must be generated first.
# For some reason, RI docs cannot be generated after any RDoc
# documents are generated.
if options[:generate_ri]
installed_gems.each do |gem|
Gem::DocManager.new(gem, options[:rdoc_args]).generate_ri
end
end
if options[:generate_rdoc]
installed_gems.each do |gem|
Gem::DocManager.new(gem, options[:rdoc_args]).generate_rdoc
end
end
if options[:test]
installed_gems.each do |spec|
gem_spec = Gem::SourceIndex.from_installed_gems.search(spec.name, spec.version.version).first
result = Gem::Validator.new.unit_test(gem_spec)
unless result.passed?
unless ask_yes_no("...keep Gem?", true) then
Gem::Uninstaller.new(spec.name, spec.version.version).uninstall
end
end
end
end
end
end
end
####################################################################
class OutdatedCommand < Command
def initialize
super 'outdated', 'Display all gems that need updates'
end
def execute
locals = Gem::SourceIndex.from_installed_gems
locals.outdated.each do |name|
local = locals.search(/^#{name}$/).last
remote = Gem::SourceInfoCache.search(/^#{name}$/).last
say "#{local.name} (#{local.version} < #{remote.version})"
end
end
end
####################################################################
class SourcesCommand < Command
def initialize
super 'sources', 'Manage the sources RubyGems will search forgems'
add_option '-a', '--add SOURCE_URI', 'Add source' do |value, options|
options[:add] = value
end
add_option '-l', '--list', 'List sources' do |value, options|
options[:list] = value
end
add_option '-r', '--remove SOURCE_URI', 'Remove source' do |value, options|
options[:remove] = value
end
end
def defaults_str
'--list'
end
def execute
if options[:add] then
source_uri = options[:add]
sice = Gem::SourceInfoCacheEntry.new nil, nil
begin
sice.refresh source_uri
rescue ArgumentError
say "#{source_uri} is not a URI"
rescue Gem::RemoteFetcher::FetchError => e
say "Error fetching #{source_uri}:\n\t#{e.message}"
else
Gem::SourceInfoCache.cache_data[source_uri] = sice
Gem::SourceInfoCache.cache.update
Gem::SourceInfoCache.cache.flush
say "#{source_uri} added to sources"
end
end
if options[:remove] then
source_uri = options[:remove]
unless Gem::SourceInfoCache.cache_data.include? source_uri then
say "source #{source_uri} not present in cache"
else
Gem::SourceInfoCache.cache_data.delete source_uri
Gem::SourceInfoCache.cache.update
Gem::SourceInfoCache.cache.flush
say "#{source_uri} removed from sources"
end
end
if options[:list] or not (options[:add] or options[:remove]) then
say "*** CURRENT SOURCES ***"
say
Gem::SourceInfoCache.cache_data.keys.each do |source_uri|
say source_uri
end
end
end
end
####################################################################
class UninstallCommand < Command
include VersionOption
include CommandAids
def initialize
super('uninstall', 'Uninstall gems from the local repository',
{ :version => "> 0" })
add_option('-a', '--[no-]all',
'Uninstall all matching versions'
) do |value, options|
options[:all] = value
end
add_option('-i', '--[no-]ignore-dependencies',
'Ignore dependency requirements while',
'uninstalling') do |value, options|
options[:ignore] = value
end
add_option('-x', '--[no-]executables',
'Uninstall applicable executables without',
'confirmation') do |value, options|
options[:executables] = value
end
add_version_option('uninstall')
end
def defaults_str
"--version '> 0' --no-force"
end
def usage
"#{program_name} GEMNAME [GEMNAME ...]"
end
def arguments
"GEMNAME name of gem to uninstall"
end
def execute
get_all_gem_names.each do |gem_name|
Gem::Uninstaller.new(gem_name, options).uninstall
end
end
end
####################################################################
class CertCommand < Command
include CommandAids
def initialize
super(
'cert',
'Adjust RubyGems certificate settings',
{
})
add_option('-a', '--add CERT', 'Add a trusted certificate.') do |value, options|
cert = OpenSSL::X509::Certificate.new(File.read(value))
Gem::Security.add_trusted_cert(cert)
puts "Added #{cert.subject.to_s}"
end
add_option('-l', '--list', 'List trusted certificates.') do |value, options|
glob_str = File::join(Gem::Security::OPT[:trust_dir], '*.pem')
Dir::glob(glob_str) do |path|
cert = OpenSSL::X509::Certificate.new(File.read(path))
# this could proably be formatted more gracefully
puts cert.subject.to_s
end
end
add_option('-r', '--remove STRING',
'Remove trusted certificates containing',
'STRING.') do |value, options|
trust_dir = Gem::Security::OPT[:trust_dir]
glob_str = File::join(trust_dir, '*.pem')
Dir::glob(glob_str) do |path|
cert = OpenSSL::X509::Certificate.new(File.read(path))
if cert.subject.to_s.downcase.index(value)
puts "Removing '#{cert.subject.to_s}'"
File.unlink(path)
end
end
end
add_option('-b', '--build EMAIL_ADDR',
'Build private key and self-signed',
'certificate for EMAIL_ADDR.') do |value, options|
vals = Gem::Security::build_self_signed_cert(value)
File::chmod(0600, vals[:key_path])
puts "Public Cert: #{vals[:cert_path]}",
"Private Key: #{vals[:key_path]}",
"Don't forget to move the key file to somewhere private..."
end
add_option('-C', '--certificate CERT',
'Certificate for --sign command.') do |value, options|
cert = OpenSSL::X509::Certificate.new(File.read(value))
Gem::Security::OPT[:issuer_cert] = cert
end
add_option('-K', '--private-key KEY',
'Private key for --sign command.') do |value, options|
key = OpenSSL::PKey::RSA.new(File.read(value))
Gem::Security::OPT[:issuer_key] = key
end
add_option('-s', '--sign NEWCERT',
'Sign a certificate with my key and',
'certificate.') do |value, options|
cert = OpenSSL::X509::Certificate.new(File.read(value))
my_cert = Gem::Security::OPT[:issuer_cert]
my_key = Gem::Security::OPT[:issuer_key]
cert = Gem::Security.sign_cert(cert, my_key, my_cert)
File::open(value, 'wb') { |file| file.write(cert.to_pem) }
end
end
def execute
end
end
####################################################################
class DependencyCommand < Command
include VersionOption
include CommandAids
def initialize
super('dependency',
'Show the dependencies of an installed gem',
{:version=>"> 0"})
add_version_option('dependency')
add_option('-r', '--[no-]reverse-dependencies',
'Include reverse dependencies in the output'
) do |value, options|
options[:reverse_dependencies] = value
end
add_option('-p', '--pipe', "Pipe Format (name --version ver)") do |value, options|
options[:pipe_format] = value
end
end
def defaults_str
"--version '> 0' --no-reverse"
end
def usage
"#{program_name} GEMNAME"
end
def arguments
"GEMNAME name of gems to show"
end
def execute
specs = {}
srcindex = SourceIndex.from_installed_gems
options[:args] << '.' if options[:args].empty?
options[:args].each do |name|
speclist = srcindex.search(name, options[:version])
if speclist.empty?
say "No match found for #{name} (#{options[:version]})"
else
speclist.each do |spec|
specs[spec.full_name] = spec
end
end
end
reverse = Hash.new { |h, k| h[k] = [] }
if options[:reverse_dependencies]
specs.values.each do |spec|
reverse[spec.full_name] = find_reverse_dependencies(spec, srcindex)
end
end
if options[:pipe_format]
specs.values.sort.each do |spec|
unless spec.dependencies.empty?
spec.dependencies.each do |dep|
puts "#{dep.name} --version '#{dep.version_requirements}'"
end
end
end
else
response = ''
specs.values.sort.each do |spec|
response << print_dependencies(spec)
unless reverse[spec.full_name].empty?
response << " Used by\n"
reverse[spec.full_name].each do |sp, dep|
response << " #{sp} (#{dep})\n"
end
end
response << "\n"
end
say response
end
end
def print_dependencies(spec, level = 0)
response = ''
response << ' ' * level + "Gem #{spec.full_name}\n"
unless spec.dependencies.empty?
# response << ' ' * level + " Requires\n"
spec.dependencies.each do |dep|
response << ' ' * level + " #{dep}\n"
end
end
response
end
# Retuns list of [specification, dep] that are satisfied by spec.
def find_reverse_dependencies(spec, srcindex)
result = []
srcindex.each do |name, sp|
sp.dependencies.each do |dep|
if spec.name == dep.name &&
dep.version_requirements.satisfied_by?(spec.version)
result << [sp.full_name, dep]
end
end
end
result
end
end
####################################################################
class CheckCommand < Command
include CommandAids
def initialize
super('check', 'Check installed gems',
{:verify => false, :alien => false})
add_option('-v', '--verify FILE',
'Verify gem file against its internal',
'checksum') do |value, options|
options[:verify] = value
end
add_option('-a', '--alien', "Report 'unmanaged' or rogue files in the",
"gem repository") do |value, options|
options[:alien] = true
end
add_option('-t', '--test', "Run unit tests for gem") do |value, options|
options[:test] = true
end
add_option('-V', '--version',
"Specify version for which to run unit tests") do |value, options|
options[:version] = value
end
end
def execute
if options[:test]
version = options[:version] || "> 0.0.0"
gem_spec = Gem::SourceIndex.from_installed_gems.search(get_one_gem_name, version).first
Gem::Validator.new.unit_test(gem_spec)
end
if options[:alien]
say "Performing the 'alien' operation"
Gem::Validator.new.alien.each do |key, val|
if(val.size > 0)
say "#{key} has #{val.size} problems"
val.each do |error_entry|
say "\t#{error_entry.path}:"
say "\t#{error_entry.problem}"
say
end
else
say "#{key} is error-free"
end
say
end
end
if options[:verify]
gem_name = options[:verify]
unless gem_name
alert_error "Must specify a .gem file with --verify NAME"
return
end
unless File.exist?(gem_name)
alert_error "Unknown file: #{gem_name}."
return
end
say "Verifying gem: '#{gem_name}'"
begin
Gem::Validator.new.verify_gem_file(gem_name)
rescue Exception => e
alert_error "#{gem_name} is invalid."
end
end
end
end # class
####################################################################
class BuildCommand < Command
include CommandAids
def initialize
super('build', 'Build a gem from a gemspec')
end
def usage
"#{program_name} GEMSPEC_FILE"
end
def arguments
"GEMSPEC_FILE name of gemspec file used to build the gem"
end
def execute
gemspec = get_one_gem_name
if File.exist?(gemspec)
specs = load_gemspecs(gemspec)
specs.each do |spec|
Gem::Builder.new(spec).build
end
return
else
alert_error "Gemspec file not found: #{gemspec}"
end
end
def load_gemspecs(filename)
if yaml?(filename)
require 'yaml'
result = []
open(filename) do |f|
begin
while spec = Gem::Specification.from_yaml(f)
result << spec
end
rescue EndOfYAMLException => e
# OK
end
end
else
result = [Gem::Specification.load(filename)]
end
result
end
def yaml?(filename)
line = open(filename) { |f| line = f.gets }
result = line =~ %r{^--- *!ruby/object:Gem::Specification}
result
end
end
####################################################################
class QueryCommand < Command
include LocalRemoteOptions
def initialize(name='query', summary='Query gem information in local or remote repositories')
super(name,
summary,
{:name=>/.*/, :domain=>:local, :details=>false}
)
add_option('-n', '--name-matches REGEXP', 'Name of gem(s) to query on matches the provided REGEXP') do |value, options|
options[:name] = /#{value}/i
end
add_option('-d', '--[no-]details', 'Display detailed information of gem(s)') do |value, options|
options[:details] = value
end
add_local_remote_options
end
def defaults_str
"--local --name-matches '.*' --no-details"
end
def execute
if local?
say
say "*** LOCAL GEMS ***"
output_query_results(Gem::cache.search(options[:name]))
end
if remote?
say
say "*** REMOTE GEMS ***"
output_query_results(Gem::SourceInfoCache.search(options[:name]))
end
end
private
def output_query_results(gemspecs)
gem_list_with_version = {}
gemspecs.flatten.each do |gemspec|
gem_list_with_version[gemspec.name] ||= []
gem_list_with_version[gemspec.name] << gemspec
end
gem_list_with_version = gem_list_with_version.sort do |first, second|
first[0].downcase <=> second[0].downcase
end
gem_list_with_version.each do |gem_name, list_of_matching|
say
list_of_matching = list_of_matching.sort_by { |x| x.version }.reverse
seen_versions = []
list_of_matching.delete_if do |item|
if(seen_versions.member?(item.version))
true
else
seen_versions << item.version
false
end
end
say "#{gem_name} (#{list_of_matching.map{|gem| gem.version.to_s}.join(", ")})"
say format_text(list_of_matching[0].summary, 68, 4)
end
end
##
# Used for wrapping and indenting text
#
def format_text(text, wrap, indent=0)
result = []
pattern = Regexp.new("^(.{0,#{wrap}})[ \n]")
work = text.dup
while work.length > wrap
if work =~ pattern
result << $1
work.slice!(0, $&.length)
else
result << work.slice!(0, wrap)
end
end
result << work if work.length.nonzero?
result.join("\n").gsub(/^/, " " * indent)
end
end
####################################################################
class ListCommand < QueryCommand
include CommandAids
def initialize
super(
'list',
'Display all gems whose name starts with STRING'
)
remove_option('--name-matches')
end
def defaults_str
"--local --no-details"
end
def usage
"#{program_name} [STRING]"
end
def arguments
"STRING start of gem name to look for"
end
def execute
string = get_one_optional_argument || ''
options[:name] = /^#{string}/i
super
end
end
####################################################################
class SearchCommand < QueryCommand
include CommandAids
def initialize
super(
'search',
'Display all gems whose name contains STRING'
)
remove_option('--name-matches')
end
def defaults_str
"--local --no-details"
end
def usage
"#{program_name} [STRING]"
end
def arguments
"STRING fragment of gem name to look for"
end
def execute
string = get_one_optional_argument
options[:name] = /#{string}/i
super
end
end
####################################################################
class UpdateCommand < Command
include InstallUpdateOptions
def initialize
super(
'update',
'Update the named gem (or all installed gems) in the local repository',
{
:generate_rdoc => true,
:generate_ri => true,
:force => false,
:test => false,
:install_dir => Gem.dir
})
add_install_update_options
add_option('--system',
'Update the RubyGems system software') do |value, options|
options[:system] = value
end
end
def defaults_str
"--rdoc --ri --no-force --no-test\n" +
"--install-dir #{Gem.dir}"
end
def arguments
"GEMNAME(s) name of gem(s) to update"
end
def execute
if options[:system]
say "Updating RubyGems..."
if ! options[:args].empty?
fail "No gem names are allowed with the --system option"
end
options[:args] = ["rubygems-update"]
else
say "Updating installed gems..."
end
hig = highest_installed_gems = {}
Gem::SourceIndex.from_installed_gems.each do |name, spec|
if hig[spec.name].nil? or hig[spec.name].version < spec.version
hig[spec.name] = spec
end
end
remote_gemspecs = Gem::SourceInfoCache.search(//)
gems_to_update = if(options[:args].empty?) then
which_to_update(highest_installed_gems, remote_gemspecs)
else
options[:args]
end
options[:domain] = :remote # install from remote source
install_command = command_manager['install']
gems_to_update.uniq.sort.each do |name|
say "Attempting remote update of #{name}"
options[:args] = [name]
install_command.merge_options(options)
install_command.execute
end
if gems_to_update.include?("rubygems-update")
latest_ruby_gem = remote_gemspecs.select { |s|
s.name == 'rubygems-update'
}.sort_by { |s|
s.version
}.last
say "Updating version of RubyGems to #{latest_ruby_gem.version}"
do_rubygems_update(latest_ruby_gem.version.to_s)
end
if(options[:system]) then
say "RubyGems system software updated"
else
say "Gems: [#{gems_to_update.uniq.sort.collect{|g| g.to_s}.join(', ')}] updated"
end
end
def do_rubygems_update(version_string)
update_dir = File.join(Gem.dir, "gems", "rubygems-update-#{version_string}")
Dir.chdir(update_dir) do
puts "Installing RubyGems #{version_string}"
system "#{Gem.ruby} setup.rb"
end
end
def which_to_update(highest_installed_gems, remote_gemspecs)
result = []
highest_installed_gems.each do |l_name, l_spec|
highest_remote_gem =
remote_gemspecs.select { |spec| spec.name == l_name }.
sort_by { |spec| spec.version }.
last
if highest_remote_gem and l_spec.version < highest_remote_gem.version
result << l_name
end
end
result
end
end
####################################################################
class CleanupCommand < Command
def initialize
super(
'cleanup',
'Clean up old versions of installed gems in the local repository',
{
:force => false,
:test => false,
:install_dir => Gem.dir
})
add_option('-d', '--dryrun', "") do |value, options|
options[:dryrun] = true
end
end
def defaults_str
"--no-dryrun"
end
def arguments
"GEMNAME(s) name of gem(s) to cleanup"
end
def execute
say "Cleaning up installed gems..."
srcindex = Gem::SourceIndex.from_installed_gems
primary_gems = {}
srcindex.each do |name, spec|
if primary_gems[spec.name].nil? or primary_gems[spec.name].version < spec.version
primary_gems[spec.name] = spec
end
end
gems_to_cleanup = []
if ! options[:args].empty?
options[:args].each do |gem_name|
specs = Gem.cache.search(/^#{gem_name}$/i)
specs.each do |spec|
gems_to_cleanup << spec
end
end
else
srcindex.each do |name, spec|
gems_to_cleanup << spec
end
end
gems_to_cleanup = gems_to_cleanup.select { |spec|
primary_gems[spec.name].version != spec.version
}
uninstall_command = command_manager['uninstall']
deplist = DependencyList.new
gems_to_cleanup.uniq.each do |spec| deplist.add(spec) end
deplist.dependency_order.each do |spec|
if options[:dryrun]
say "Dry Run Mode: Would uninstall #{spec.full_name}"
else
say "Attempting uninstall on #{spec.full_name}"
options[:args] = [spec.name]
options[:version] = "= #{spec.version}"
options[:executables] = true
uninstall_command.merge_options(options)
begin
uninstall_command.execute
rescue Gem::DependencyRemovalException => ex
say "Unable to uninstall #{spec.full_name} ... continuing with remaining gems"
end
end
end
say "Clean Up Complete"
end
end
####################################################################
class PristineCommand < Command
include VersionOption
include CommandAids
def initialize
super('pristine',
'Restores gem directories to pristine condition from files located in the gem cache',
{
:version => "> 0.0.0"
})
add_option('--all',
'Restore all installed gems to pristine', 'condition'
) do |value, options|
options[:all] = value
end
add_version_option('restore to', 'pristine condition')
end
def defaults_str
"--all"
end
def usage
"#{program_name} [args]"
end
def arguments
"GEMNAME The gem to restore to pristine condition (unless --all)"
end
def execute
say "Restoring gem(s) to pristine condition..."
if options[:all]
all_gems = true
specs = Gem::SourceIndex.from_installed_gems.collect do |name, spec|
spec
end
else
all_gems = false
gem_name = get_one_gem_name
specs = Gem::SourceIndex.from_installed_gems.search(gem_name, options[:version])
end
if specs.empty?
fail "Failed to find gem #{gem_name} #{options[:version]} to restore to pristine condition"
end
install_dir = Gem.dir # TODO use installer option
raise Gem::FilePermissionError.new(install_dir) unless File.writable?(install_dir)
gems_were_pristine = true
specs.each do |spec|
installer = Gem::Installer.new nil, :wrappers => true # HACK ugly TODO use installer option
gem_file = File.join(install_dir, "cache", "#{spec.full_name}.gem")
security_policy = nil # TODO use installer option
format = Gem::Format.from_file_by_path(gem_file, security_policy)
target_directory = File.join(install_dir, "gems", format.spec.full_name).untaint
pristine_files = format.file_entries.collect {|data| data[0]["path"]}
file_map = {}
format.file_entries.each {|entry, file_data| file_map[entry["path"]] = file_data}
require 'fileutils'
Dir.chdir target_directory do
deployed_files = Dir.glob(File.join("**", "*")) +
Dir.glob(File.join("**", ".*"))
to_redeploy = (pristine_files - deployed_files).collect {|path| path.untaint}
if to_redeploy.length > 0
gems_were_pristine = false
say "Restoring #{to_redeploy.length} file#{to_redeploy.length == 1 ? "" : "s"} to #{spec.full_name}..."
to_redeploy.each do |path|
say " #{path}"
FileUtils.mkdir_p File.dirname(path)
File.open(path, "wb") do |out|
out.write file_map[path]
end
end
end
end
installer.generate_bin spec, install_dir
end
say "Rebuilt all bin stubs"
if gems_were_pristine
if all_gems
say "All installed gem files are already in pristine condition"
else
say "#{specs[0].full_name} is already in pristine condition"
end
else
if all_gems
say "All installed gem files restored to pristine condition"
else
say "#{specs[0].full_name} restored to pristine condition"
end
end
end
end
####################################################################
class RDocCommand < Command
include VersionOption
include CommandAids
def initialize
super('rdoc',
'Generates RDoc for pre-installed gems',
{
:version => "> 0.0.0",
:include_rdoc => true,
:include_ri => true,
})
add_option('--all',
'Generate RDoc/RI documentation for all',
'installed gems') do |value, options|
options[:all] = value
end
add_option('--[no-]rdoc',
'Include RDoc generated documents') do
|value, options|
options[:include_rdoc] = value
end
add_option('--[no-]ri',
'Include RI generated documents'
) do |value, options|
options[:include_ri] = value
end
add_version_option('rdoc')
end
def defaults_str
"--version '> 0.0.0' --rdoc --ri"
end
def usage
"#{program_name} [args]"
end
def arguments
"GEMNAME The gem to generate RDoc for (unless --all)"
end
def execute
if options[:all]
specs = Gem::SourceIndex.from_installed_gems.collect { |name, spec|
spec
}
else
gem_name = get_one_gem_name
specs = Gem::SourceIndex.from_installed_gems.search(
gem_name, options[:version])
end
if specs.empty?
fail "Failed to find gem #{gem_name} to generate RDoc for #{options[:version]}"
end
if options[:include_ri]
specs.each do |spec|
Gem::DocManager.new(spec).generate_ri
end
end
if options[:include_rdoc]
specs.each do |spec|
Gem::DocManager.new(spec).generate_rdoc
end
end
true
end
end
####################################################################
class EnvironmentCommand < Command
include CommandAids
def initialize
super('environment', 'Display information about the RubyGems environment')
end
def usage
"#{program_name} [args]"
end
def arguments
args = <<-EOF
packageversion display the package version
gemdir display the path where gems are installed
gempath display path used to search for gems
version display the gem format version
remotesources display the remote gem servers
<omitted> display everything
EOF
return args.gsub(/^\s+/, '')
end
def execute
out = ''
arg = options[:args][0]
if begins?("packageversion", arg)
out = Gem::RubyGemsPackageVersion.to_s
elsif begins?("version", arg)
out = Gem::RubyGemsVersion.to_s
elsif begins?("gemdir", arg)
out = Gem.dir
elsif begins?("gempath", arg)
Gem.path.collect { |p| out << "#{p}\n" }
elsif begins?("remotesources", arg)
require 'sources'
out << Gem.sources.join("\n") << "\n"
elsif arg
fail Gem::CommandLineError, "Unknown enviroment option [#{arg}]"
else
out = "RubyGems Environment:\n"
out << " - VERSION: #{Gem::RubyGemsVersion} (#{Gem::RubyGemsPackageVersion})\n"
out << " - INSTALLATION DIRECTORY: #{Gem.dir}\n"
out << " - GEM PATH:\n"
Gem.path.collect { |p| out << " - #{p}\n" }
out << " - REMOTE SOURCES:\n"
require 'sources'
Gem.sources.collect do |s|
out << " - #{s}\n"
end
end
say out
true
end
end
####################################################################
class SpecificationCommand < Command
include VersionOption
include LocalRemoteOptions
include CommandAids
def initialize
super('specification', 'Display gem specification (in yaml)',
{:domain=>:local, :version=>"> 0.0.0"})
add_version_option('examine')
add_local_remote_options
add_option('--all', 'Output specifications for all versions of',
'the gem') do |value, options|
options[:all] = true
end
end
def defaults_str
"--local --version '(latest)'"
end
def usage
"#{program_name} GEMFILE"
end
def arguments
"GEMFILE Name of a .gem file to examine"
end
def execute
if local?
gem = get_one_gem_name
gem_specs = Gem::SourceIndex.from_installed_gems.search(gem, options[:version])
unless gem_specs.empty?
require 'yaml'
output = lambda { |spec| say spec.to_yaml; say "\n" }
if options[:all]
gem_specs.each(&output)
else
spec = gem_specs.sort_by { |spec| spec.version }.last
output[spec]
end
else
alert_error "Unknown gem #{gem}"
end
end
if remote?
say "(Remote 'info' operation is not yet implemented.)"
# NOTE: when we do implement remote info, make sure we don't
# duplicate huge swabs of local data. If it's the same, just
# say it's the same.
end
end
end
####################################################################
class UnpackCommand < Command
include VersionOption
include CommandAids
def initialize
super(
'unpack',
'Unpack an installed gem to the current directory',
{ :version => '> 0' }
)
add_version_option('unpack')
end
def defaults_str
"--version '> 0'"
end
def usage
"#{program_name} GEMNAME"
end
def arguments
"GEMNAME Name of the gem to unpack"
end
# TODO: allow, e.g., 'gem unpack rake-0.3.1'. Find a general
# solution for this, so that it works for uninstall as well. (And
# check other commands at the same time.)
def execute
gemname = get_one_gem_name
path = get_path(gemname, options[:version])
if path
require 'fileutils'
target_dir = File.basename(path).sub(/\.gem$/, '')
FileUtils.mkdir_p target_dir
Installer.new(path).unpack(File.expand_path(target_dir))
say "Unpacked gem: '#{target_dir}'"
else
alert_error "Gem '#{gemname}' not installed."
end
end
# Return the full path to the cached gem file matching the given
# name and version requirement. Returns 'nil' if no match.
# Example:
#
# get_path('rake', '> 0.4') # -> '/usr/lib/ruby/gems/1.8/cache/rake-0.4.2.gem'
# get_path('rake', '< 0.1') # -> nil
# get_path('rak') # -> nil (exact name required)
#
# TODO: This should be refactored so that it's a general service.
# I don't think any of our existing classes are the right place
# though. Just maybe 'Cache'?
#
# TODO: It just uses Gem.dir for now. What's an easy way to get
# the list of source directories?
#
def get_path(gemname, version_req)
return gemname if gemname =~ /\.gem$/i
specs = SourceIndex.from_installed_gems.search(gemname, version_req)
selected = specs.sort_by { |s| s.version }.last
return nil if selected.nil?
# We expect to find (basename).gem in the 'cache' directory.
# Furthermore, the name match must be exact (ignoring case).
if gemname =~ /^#{selected.name}$/i
filename = selected.full_name + '.gem'
return File.join(Gem.dir, 'cache', filename)
else
return nil
end
end
end
####################################################################
class HelpCommand < Command
include CommandAids
def initialize
super('help', "Provide help on the 'gem' command")
end
def usage
"#{program_name} ARGUMENT"
end
def arguments
args = <<-EOF
commands List all 'gem' commands
examples Show examples of 'gem' usage
<command> Show specific help for <command>
EOF
return args.gsub(/^\s+/, '')
end
def execute
arg = options[:args][0]
if begins?("commands", arg)
out = []
out << "GEM commands are:"
out << nil
margin_width = 4
desc_width = command_manager.command_names.collect {|n| n.size}.max + 4
summary_width = 80 - margin_width - desc_width
wrap_indent = ' ' * (margin_width + desc_width)
format = "#{' ' * margin_width}%-#{desc_width}s%s"
command_manager.command_names.each do |cmd_name|
summary = command_manager[cmd_name].summary
summary = wrap(summary, summary_width).split "\n"
out << sprintf(format, cmd_name, summary.shift)
until summary.empty? do
out << "#{wrap_indent}#{summary.shift}"
end
end
out << nil
out << "For help on a particular command, use 'gem help COMMAND'."
out << nil
out << "Commands may be abbreviated, so long as they are unambiguous."
out << "e.g. 'gem i rake' is short for 'gem install rake'."
say out.join("\n")
elsif begins?("options", arg)
say Gem::HELP
elsif begins?("examples", arg)
say Gem::EXAMPLES
elsif options[:help]
command = command_manager[options[:help]]
if command
# help with provided command
command.invoke("--help")
else
alert_error "Unknown command #{options[:help]}. Try 'gem help commands'"
end
elsif arg
possibilities = command_manager.find_command_possibilities(arg.downcase)
if possibilities.size == 1
command = command_manager[possibilities.first]
command.invoke("--help")
elsif possibilities.size > 1
alert_warning "Ambiguous command #{arg} (#{possibilities.join(', ')})"
else
alert_warning "Unknown command #{arg}. Try gem help commands"
end
else
say Gem::HELP
end
end
end
####################################################################
class ContentsCommand < Command
include CommandAids
include VersionOption
def initialize
super(
'contents',
'Display the contents of the installed gems',
{ :list => true, :specdirs => [] })
add_version_option('contents')
add_option("-l","--list",'List the files inside a Gem') do |v,o|
o[:list] = true
end
add_option('-s','--spec-dir a,b,c', Array, "Search for gems under specific paths") do |v,o|
o[:specdirs] = v
end
add_option('-V','--verbose','Be verbose when showing status') do |v,o|
o[:verbose] = v
end
end
def execute(io=STDOUT)
if options[:list]
version = options[:version] || "> 0.0.0"
gem = get_one_gem_name
s = options[:specdirs].map do |i|
[i, File.join(i,"specifications")]
end.flatten
if s.empty?
s = Gem::SourceIndex.installed_spec_directories
path_kind = "default gem paths"
system = true
else
path_kind = "specified path"
system = false
end
si = Gem::SourceIndex.from_gems_in(*s)
gem_spec = si.search(gem, version).last
unless gem_spec
io.puts "Unable to find gem '#{gem}' in #{path_kind}"
if options[:verbose]
io.puts "\nDirectories searched:"
s.each do |p|
io.puts p
end
end
return
end
# show the list of files.
gem_spec.files.each do |f|
io.puts File.join(gem_spec.full_gem_path, f)
end
end
end
end
end # module
######################################################################
# Documentation Constants
#
module Gem
HELP = %{
RubyGems is a sophisticated package manager for Ruby. This is a
basic help message containing pointers to more information.
Usage:
gem -h/--help
gem -v/--version
gem command [arguments...] [options...]
Examples:
gem install rake
gem list --local
gem build package.gemspec
gem help install
Further help:
gem help commands list all 'gem' commands
gem help examples show some examples of usage
gem help <COMMAND> show help on COMMAND
(e.g. 'gem help install')
Further information:
http://rubygems.rubyforge.org
}.gsub(/^ /, "")
EXAMPLES = %{
Some examples of 'gem' usage.
* Install 'rake', either from local directory or remote server:
gem install rake
* Install 'rake', only from remote server:
gem install rake --remote
* Install 'rake' from remote server, and run unit tests,
and generate RDocs:
gem install --remote rake --test --rdoc --ri
* Install 'rake', but only version 0.3.1, even if dependencies
are not met, and into a specific directory:
gem install rake --version 0.3.1 --force --install-dir $HOME/.gems
* List local gems whose name begins with 'D':
gem list D
* List local and remote gems whose name contains 'log':
gem search log --both
* List only remote gems whose name contains 'log':
gem search log --remote
* Uninstall 'rake':
gem uninstall rake
* Create a gem:
See http://rubygems.rubyforge.org/wiki/wiki.pl?CreateAGemInTenMinutes
* See information about RubyGems:
gem environment
}.gsub(/^ /, "")
end
|
# Print all odd numbers from 1 to 99, inclusive, to the console, with each number on a separate line.
(1..99).each { |n| puts n if n.odd?}
#LS Solution
value = 1
while value <= 99
puts value
value += 2
end
|
class ActiveRecord::Base
def self.magic_associations
x = self.column_names.select { |n| n.ends_with? '_id' }
x.each do |fk|
assoc_name = fk[0, fk.length - 3]
belongs_to assoc_name.to_sym
assoc_name.classify.constantize.send(:has_many, self.name.underscore.pluralize.to_sym, dependent: :destroy)
end
end
def inspect
"#<#{self.class.name} #{attributes}>"
end
def self.read(args = nil)
if args.nil?
all
elsif args.is_a?(Integer)
find_by(id: args)
elsif args.is_a?(String) && args.to_i > 0 && !args.index(' ')
find_by(id: args)
elsif args.is_a?(Hash) && args.keys.count == 1 && args.keys[0].to_sym == :id
find_by(args)
else
where(args)
end
end
def self.sample
offset(rand(0...count)).first
end
def self.none?
self.count == 0
end
def self.to_ez
s = self.name + ":\n"
columns.each do |column|
s << " - #{column.name}: #{column.type}\n" unless column.name == 'id'
end
s
end
def self.dump_tables_to_ez
(connection.tables - ['schema_migrations']).each do |table|
puts table.classify.constantize.to_ez
end
end
end
|
require File.expand_path("../../../lib/tasks/metrical_workaround", __FILE__)
include MetricalWorkaround
describe "metrical_preparation" do
describe "substitute" do
it "should replace one argument" do
substitute("before_filter :not_current_user, only: :destroy").should ==
"before_filter :not_current_user, :only => :destroy"
end
it "should replace argument with list" do
substitute("before_filter :guest_user, only: [:new, :create]").should ==
"before_filter :guest_user, :only => [:new, :create]"
end
it "should replace in validation" do
substitute("validates :password_confirmation, presence: true").should ==
"validates :password_confirmation, :presence => true"
end
it "should replace in association" do
substitute("has_many :microposts, dependent: :destroy").should ==
"has_many :microposts, :dependent => :destroy"
end
it "should not replace the encoding declaration" do
substitute("# encoding: UTF-8").should ==
"# encoding: UTF-8"
end
it "should also leave comments alone" do
substitute("# These ... rules are supported but not enabled by default:\n")
.should == "# These ... rules are supported but not enabled by default:\n"
end
end
end |
Lita.configure do |config|
config.robot.name = "Advisor"
# The locale code for the language to use.
config.robot.locale = :en
config.robot.mention_name = "advisor"
config.robot.alias = ":"
config.robot.log_level = :info
config.robot.admins = ["U049ZRWKF"]
config.robot.adapter = :slack
config.adapters.slack.token = ENV["SLACK_TOKEN"]
config.redis[:url] = ENV["REDISCLOUD_URL"]
config.http.port = ENV["PORT"]
end
|
module Bitcourier
class Address < Struct.new(:ip, :port)
private :ip=, :port=
def initialize(ip, port)
self.ip = ip || raise(ArgumentError, 'IP must be present')
self.port = port || raise(ArgumentError, 'port must be present')
end
def to_s
"#{ip}:#{port}"
end
end
end
|
require_relative '../lib/intervals/genome_region'
require 'rspec/given'
describe GenomeRegion do
describe '#initialize' do
context 'with start < end' do
When(:region) { GenomeRegion.new('chr1', '+', 100, 110) }
Then { region.should_not have_failed }
end
context 'with start > end' do
When(:region) { GenomeRegion.new('chr1', '+', 100, 97) }
Then { region.should have_failed }
end
context 'with start == end' do
When(:region) { GenomeRegion.new('chr1', '+', 100, 100) }
Then { region.should have_failed }
end
end
Given(:region) { GenomeRegion.new('chr1', '+', 100, 110) }
Given(:same_region) { GenomeRegion.new('chr1', '+', 100, 110) }
Given(:region_inside) { GenomeRegion.new('chr1', '+', 103, 107) }
Given(:region_inside_extend_to_end) { GenomeRegion.new('chr1', '+', 103, 110) }
Given(:region_inside_extend_from_start) { GenomeRegion.new('chr1', '+', 100, 103) }
Given(:region_on_another_strand) { GenomeRegion.new('chr1', '-', 103, 107) }
Given(:region_on_another_chromosome) { GenomeRegion.new('chr2', '+', 103, 107) }
Given(:region_from_inside_to_outside_after_end) { GenomeRegion.new('chr1', '+', 103, 113) }
Given(:region_from_outside_before_start_to_inside) { GenomeRegion.new('chr1', '+', 97, 103) }
Given(:region_containing) { GenomeRegion.new('chr1', '+', 97, 113) }
Given(:region_outside_left) { GenomeRegion.new('chr1', '+', 97, 99) }
Given(:region_outside_right) { GenomeRegion.new('chr1', '+', 113, 117) }
Given(:region_outside_extend_from_end) { GenomeRegion.new('chr1', '+', 110, 113) }
Given(:region_outside_extend_to_start) { GenomeRegion.new('chr1', '+', 97, 100) }
Given(:all_region_types) {
[ region, same_region, region_inside, region_inside_extend_to_end, region_inside_extend_from_start,
region_on_another_strand, region_on_another_chromosome,
region_from_inside_to_outside_after_end, region_from_outside_before_start_to_inside,
region_containing,
region_outside_left, region_outside_right,
region_outside_extend_from_end, region_outside_extend_to_start]
}
describe '#intersect?' do
Then{
all_region_types.each{|second_region|
region.intersect?(second_region).should == second_region.intersect?(region)
}
}
Then{
all_region_types.each{|second_region|
region.intersect?(second_region).should be_true if region.intersection(second_region)
}
}
Then{
all_region_types.each{|second_region|
region.intersect?(second_region).should be_false unless region.intersection(second_region)
}
}
end
describe '#intersection' do
Then{ region.intersection(region).should == region }
Then{ region.intersection(same_region).should == region }
Then{ region.intersection(region_inside).should == region_inside }
Then{ region.intersection(region_inside_extend_to_end).should == region_inside_extend_to_end }
Then{ region.intersection(region_inside_extend_from_start).should == region_inside_extend_from_start }
Then{ region.intersection(region_on_another_strand).should == nil }
Then{ region.intersection(region_on_another_chromosome).should == nil }
Then{ region.intersection(region_from_inside_to_outside_after_end).should == GenomeRegion.new('chr1', '+', 103, 110) }
Then{ region.intersection(region_from_outside_before_start_to_inside).should == GenomeRegion.new('chr1', '+', 100, 103) }
Then{ region.intersection(region_containing).should == region }
Then{ region.intersection(region_outside_left).should == nil }
Then{ region.intersection(region_outside_right).should == nil }
Then{ region.intersection(region_outside_extend_from_end).should == nil }
Then{ region.intersection(region_outside_extend_to_start).should == nil }
Then{
all_region_types.each{|second_region|
region.intersection(second_region).should == second_region.intersection(region)
}
}
end
describe '#contain?' do
Then{ region.contain?(region).should be_true }
Then{ region.contain?(same_region).should be_true }
Then{ region.contain?(region_inside).should be_true }
Then{ region.contain?(region_inside_extend_to_end).should be_true }
Then{ region.contain?(region_inside_extend_from_start).should be_true }
Then{ region.contain?(region_on_another_strand).should be_false }
Then{ region.contain?(region_on_another_chromosome).should be_false }
Then{ region.contain?(region_from_inside_to_outside_after_end).should be_false }
Then{ region.contain?(region_from_outside_before_start_to_inside).should be_false }
Then{ region.contain?(region_containing).should be_false }
Then{ region.contain?(region_outside_left).should be_false }
Then{ region.contain?(region_outside_right).should be_false }
Then{ region.contain?(region_outside_extend_from_end).should be_false }
Then{ region.contain?(region_outside_extend_to_start).should be_false }
end
describe '#annotation' do
Then{ region.annotation.should == 'chr1:100..110,+' }
Then{ region_on_another_chromosome.annotation.should == 'chr2:103..107,+' }
Then{ region_on_another_strand.annotation.should == 'chr1:103..107,-' }
end
describe '#length' do
Then {GenomeRegion.new('chr1', '+', 103, 104).length == 1 }
Then {GenomeRegion.new('chr1', '+', 103, 106).length == 3 }
Then {GenomeRegion.new('chr1', '-', 103, 106).length == 3 }
end
describe '.new_by_annotation' do
Then {
all_region_types.each{|region|
region.should == GenomeRegion.new_by_annotation(region.annotation)
}
}
end
describe '==' do
Given(:another_pos_start) { GenomeRegion.new('chr1', '+', 103, 110) }
Given(:another_pos_end) { GenomeRegion.new('chr1', '+', 100, 107) }
Given(:another_chromosome) { GenomeRegion.new('chrY', '+', 100, 110) }
Given(:another_strand) { GenomeRegion.new('chr1', '-', 100, 110) }
Then{ region.should == same_region}
Then{ region.should_not == another_pos_start}
Then{ region.should_not == another_pos_end}
Then{ region.should_not == another_chromosome}
Then{ region.should_not == another_strand}
end
describe 'hash/eql? ability' do
Given(:hash_by_region) { {region => 'first region', region_inside => 'another region'} }
Then{ hash_by_region.should have_key(region) }
Then{ hash_by_region.should have_key(region) }
Then{ hash_by_region.should have_key(same_region) }
Then{ hash_by_region[region].should be_eql hash_by_region[same_region] }
Then{ hash_by_region.should have_key(region_inside) }
Then{ hash_by_region.should_not have_key(region_containing) }
end
describe 'Comparable' do
Then{ (region <=> region_on_another_strand).should be_nil }
Then{ (region <=> region_on_another_chromosome).should be_nil }
shared_examples 'compare regions' do
Then { (subject_region <=> same_as_subject_region).should == 0 }
Then { (subject_region <=> region_right_to_subject).should == -1 }
Then { (subject_region <=> region_left_to_subject).should == 1 }
Then { (subject_region <=> region_right_to_subject_joint).should == -1 }
Then { (subject_region <=> region_left_to_subject_joint).should == 1 }
Then { (subject_region <=> region_inside_of_subject).should be_nil }
Then { (subject_region <=> region_inside_of_subject_left_joint).should be_nil }
Then { (subject_region <=> region_inside_of_subject_right_joint).should be_nil }
Then { (subject_region <=> region_inside_to_outside_of_subject).should be_nil }
Then { (subject_region <=> region_outside_to_inside_of_subject).should be_nil }
Then{ subject_region.should <= same_as_subject_region }
Then{ subject_region.should_not < same_as_subject_region }
Then{ subject_region.should >= same_as_subject_region }
Then{ subject_region.should_not > same_as_subject_region }
Then{ subject_region.should < region_right_to_subject }
Then{ subject_region.should <= region_right_to_subject }
Then{ subject_region.should_not > region_right_to_subject }
Then{ subject_region.should_not >= region_right_to_subject }
end
context "On + strand" do
Given(:subject_region) { GenomeRegion.new('chr1', '+', 100, 110) }
Given(:same_as_subject_region) { GenomeRegion.new('chr1', '+', 100, 110) }
Given(:region_right_to_subject) { GenomeRegion.new('chr1', '+', 113, 117) }
Given(:region_left_to_subject) { GenomeRegion.new('chr1', '+', 93, 97) }
Given(:region_right_to_subject_joint) { GenomeRegion.new('chr1', '+', 110, 117) }
Given(:region_left_to_subject_joint) { GenomeRegion.new('chr1', '+', 93, 100) }
Given(:region_inside_of_subject) { GenomeRegion.new('chr1', '+', 103, 107) }
Given(:region_inside_of_subject_left_joint) { GenomeRegion.new('chr1', '+', 100, 107) }
Given(:region_inside_of_subject_right_joint) { GenomeRegion.new('chr1', '+', 103, 110) }
Given(:region_inside_to_outside_of_subject) { GenomeRegion.new('chr1', '+', 103, 113) }
Given(:region_outside_to_inside_of_subject) { GenomeRegion.new('chr1', '+', 97, 103) }
include_examples 'compare regions'
end
context "On - strand" do
Given(:subject_region) { GenomeRegion.new('chr1', '-', 100, 110) }
Given(:same_as_subject_region) { GenomeRegion.new('chr1', '-', 100, 110) }
Given(:region_left_to_subject) { GenomeRegion.new('chr1', '-', 113, 117) }
Given(:region_right_to_subject) { GenomeRegion.new('chr1', '-', 93, 97) }
Given(:region_left_to_subject_joint) { GenomeRegion.new('chr1', '-', 110, 117) }
Given(:region_right_to_subject_joint) { GenomeRegion.new('chr1', '-', 93, 100) }
Given(:region_inside_of_subject) { GenomeRegion.new('chr1', '-', 103, 107) }
Given(:region_inside_of_subject_right_joint) { GenomeRegion.new('chr1', '-', 100, 107) }
Given(:region_inside_of_subject_left_joint) { GenomeRegion.new('chr1', '-', 103, 110) }
Given(:region_outside_to_inside_of_subject) { GenomeRegion.new('chr1', '-', 103, 113) }
Given(:region_inside_to_outside_of_subject) { GenomeRegion.new('chr1', '-', 97, 103) }
include_examples 'compare regions'
end
end
end |
class AddStakeholdingPercentageToOwnerships < ActiveRecord::Migration[5.0]
def change
add_column :ownerships, :stakeholding_percentage, :decimal
end
end
|
class UsersController < ApplicationController
helper_method :temporary_user
before_filter :stop_unauthenticated_user, only: [:edit, :update]
# GET /users
# GET /users.json
def index
# this is doig a SQL command that will get everything from the user table
# but this first goes to the modal to makse sure the data is allowed to get by usinf attr_accesible
# or in c# this would be a propertie to control data in the database not in a field
@users = User.all
# this format function renders the modal data into json or html or xml for your views
respond_to do |format|
format.html # index.html.erb
format.json { render json: @users }
end
end
# GET /users/1
# GET /users/1.json
def show
@user = User.find_by_user_name(params[:id])
session[:operator_id] = @user.id
@temporary_user = @user
end
# GET /users/new
# GET /users/new.json
def new
@user = User.new
respond_to do |format|
format.html # new.html.erb
format.json { render json: @user }
end
end
# GET /users/1/edit
def edit
@user = User.find_by_user_name(params[:id])
end
# POST /users
# POST /users.json
def create
@user = User.new(params[:user])
if @user.save
session[:user_id] = @user.id # this is setting the @user varible that has all the user info to the sessions
session[:operator_id] = @user.id
redirect_to user_path(:id => @user.user_name)
else
render "new"
end
end
# PUT /users/1
# PUT /users/1.json
def update
@user = User.find_by_user_name(params[:id])
respond_to do |format|
if @user.update_attributes(params[:user])
format.html { redirect_to @user, notice: 'User was successfully updated.' }
format.json { head :no_content }
else
format.html { render action: "edit" }
format.json { render json: @user.errors, status: :unprocessable_entity }
end
end
end
# DELETE /users/1
# DELETE /users/1.json
def destroy
@user = User.find_by_user_name(params[:id])
@user.destroy
respond_to do |format|
format.html { redirect_to users_url }
format.json { head :no_content }
end
end
end
|
class BillPDF < Prawn::Document
include ActionView::Helpers::NumberHelper
include BillHelper
def initialize(bill)
@bill = bill
super(page_size: 'A4', page_layout: :portrait)
draw_header
move_down 30
draw_subscription_info
end
def draw_header
text 'Latest Bill', size: 32
fill_color '646464'
draw_text "Due #{date_string(@bill[:statement][:due])}", size: 16, at: [145, y-22]
fill_color '000000'
draw_text currency(@bill[:total]), size: 18, at: [460,y-22]
stroke_horizontal_rule
end
def draw_subscription_info
text 'Packages', size: 18
move_down 10
packages = @bill[:package][:subscriptions].map { |s| [s[:name], currency(s[:cost])] }
table(packages, cell_style: {borders: [:top, :bottom]}, column_widths: [470, 50])
move_down 52
draw_text currency(@bill[:package][:total]), at: [475, y], style: :bold
end
end
|
class HotreadsService
HOT_READS_URL = 'https://hotreads-laszlo.herokuapp.com'
HOT_READS_ENDPOINT_LINK_CREATE = '/api/v1/links'
HOT_READS_ENDPOINT_LINK_INDEX = '/api/v1/links'
def initialize
@conn = Faraday.new(:url => HOT_READS_URL)
end
def send_link(url)
@conn.post HOT_READS_ENDPOINT_LINK_CREATE, { :url => url }
end
def get_top10
response = @conn.get HOT_READS_ENDPOINT_LINK_INDEX
top10 = JSON.parse(response.body).map do |hotreads_link|
hotreads_link['url']
end
end
end |
# frozen_string_literal: true
# == Schema Information
#
# Table name: challenges
#
# id :integer not null, primary key
# record_book_id :integer not null
# name :string not null
# created_at :datetime not null
# updated_at :datetime not null
# points_completion :integer not null
# points_first :integer
# points_second :integer
# points_third :integer
# completions_count :integer default(0), not null
# position :integer not null
# challenge_type :integer not null
#
# Indexes
#
# index_challenges_on_record_book_id (record_book_id)
#
FactoryBot.define do
factory :challenge do
record_book
challenge_type :everyone
name { Faker::Name.first_name }
points_completion { Faker::Number.between 0, 50 }
trait(:published) { association :record_book, :published }
end
end
|
class UserMailer < ActionMailer::Base
default from: "mirafloristeresina@gmail.com"
def test(email)
mail(:to => email, :subject => "Hello World!")
end
end
|
class Issue < ActiveRecord::Base
belongs_to :project
validates :name, presence: true
validates :project, associated: true
end
|
#codename = node[:lsb][:codename]
action :add do
Chef::Log.info("Adding repository for: #{new_resource.name}")
# amend sources_dir on line below
# sources_dir = '/home/bobg'
sources_dir = '/etc/apt/sources.list.d'
template "#{sources_dir}/#{new_resource.name}-#{node[:lsb][:codename]}.list" do
source "#{new_resource.name}.erb"
mode "0644"
owner "root"
group "root"
variables({:codename => node[:lsb][:codename]})
# variables({:codename => "lucid"})
end
if new_resource.key.nil? then
Chef::Log.debug("#{new_resource.name} key attribute is nil")
else
Chef::Log.debug("#{new_resource.name} key is: #{new_resource.key}")
found = `apt-key list` =~ /#{new_resource.key}/
if found then
Chef::Log.debug("#{new_resource.name} key: #{new_resource.key} found at #{found}")
else
Chef::Log.debug("#{new_resource.name} key: #{new_resource.key} NOT found")
case
when new_resource.keyserver
execute "Install #{new_resource.name} key from keyserver #{new_resource.keyserver}" do
command "apt-key adv --keyserver #{new_resource.keyserver} --recv-keys #{new_resource.key}"
user "root"
action :run
end
when new_resource.url
execute "Install #{new_resource.name} key from #{new_resource.url}" do
command "wget -q #{new_resource.url} -O- | apt-key add -"
user "root"
action :run
end
else
Chef::Log.error("#{new_resource.name} key not found and both keyserver and URL attribute is nil")
end
# if new_resource.keyserver.nil? then
# Chef::Log.error("#{new_resource.name} key not found and keyserver attribute is nil")
# else
# #look up apt add-key command and execute it here on the keyserver
# end
end
end
end
|
require 'spec_helper'
describe UserWithOpt, type: :model do
describe "gender" do
let(:user) { UserWithOpt.new(gender: gender) }
context "testing :no_empty_string" do
context "when blank" do
let(:gender) { "" }
it "should return a Gender object" do
expect(user.gender).to be_an_instance_of(Genderize::Gender)
end
it "should be blank?" do
expect(user.gender).to be_blank
end
it "should keep the stored value as nil" do
expect(user[:gender]).to be_nil
end
end
context "when nil" do
let(:gender) { nil }
it "should return a Gender object" do
expect(user.gender).to be_an_instance_of(Genderize::Gender)
end
it "should be blank?" do
expect(user.gender).to be_blank
end
it "should keep the stored value as nil" do
expect(user[:gender]).to be_nil
end
end
end
context "testing :set_invalid_to_nil" do
context "when something unexpected" do
let(:gender) { "something unexpected" }
it "should return a Gender object" do
expect(user.gender).to be_an_instance_of(Genderize::Gender)
end
it "should be blank?" do
expect(user.gender).to be_blank
end
it "should keep the stored value as nil" do
expect(user[:gender]).to be_nil
end
end
end
end
end
|
require 'rails_helper'
describe 'Academics::pagination', type: :feature do
describe '#pagination' do
context 'when finds the last academic on second page' do
it 'finds the last academic', js: true do
responsible = create(:responsible)
login_as(responsible, scope: :professor)
create_list(:academic, 30)
visit responsible_academics_path
academic = Academic.order(:name).last
click_link(2)
expect(page).to have_contents([academic.name,
academic.email,
academic.ra,
academic.created_at.strftime('%d/%m/%Y')])
end
end
end
end
|
# https://github.com/flori/json/issues/399#issuecomment-734863279
# Fix for chatty warning:
# json/common.rb:155: warning: Using the last argument as keyword parameters is deprecated
module JSON
module_function
def parse(source, opts = {})
Parser.new(source, **opts).parse
end
end
|
ActiveAdmin.register Event do
menu label: "Events"
permit_params :title, :date, :link
filter :title
index do
selectable_column
id_column
column :title
column :date
column :link
column :updated_at
column :created_at
actions defaults: true do
end
end
form do |f|
f.inputs do
f.input :title
f.input :link
f.input :date, as: :datepicker, datepicker_options: { timepicker: true, format: 'Y-m-d H:i' }
end
f.actions
end
end |
class Player
attr_accessor :number, :lives
def initialize(number)
@number = number
@lives = 3
end
end |
class Trinary
attr_reader :input
def initialize(input)
@input = valid?(input) ? input.to_i.digits : [0]
end
def to_decimal
input
.map.with_index { |digit, index| digit * 3**index }
.reduce(:+)
end
def valid?(input)
/\A[0-2]+\z/.match?(input)
end
end
|
class EnumerationDeclaration < ASTNode
def declare
comments + "class #{normalized_class_name} < IControl::Base::Enumeration; end"
end
end
class EnumerationMember < ASTNode; end
|
require 'forwardable'
class Course::ContentUpdater
include EventLogging
extend Forwardable
attr_reader :course
def_delegators :@course, :repo_dir, :assets_dir, :xml_file_path
def initialize(course)
@course = course
end
def update
cleanup
course.repo.update
xml = course.compiler.course_xml
write_to_xml_repo(xml)
update_database
course.update_attributes current_commit: course.repo.current_commit
sync_assets
log_event("course.content-update",{
course_id: course.id,
current_commit: course.current_commit
})
end
def sync_assets
puts "making assets avaiable for: #{course.name}"
from_dir = repo_dir.to_s
# /public/courses/:course_name/:lesson_name
to_dir = assets_dir.to_s
system "mkdir", "-p", to_dir
# The trailing "/" indicates to rsync that we want to copy the content to the
# destination without creating an additional sub-directory.
cmd = ["rsync", "-Pa", from_dir.to_s + "/", to_dir.to_s]
p cmd
system *cmd
end
def cleanup
# don't really need to do any cleanup.
end
def write_to_xml_repo(data)
f = File.new(xml_file_path, "w")
f.write(data)
f.close
end
def update_database
Course::Updater::DataUpdater.new(course).update
end
end
|
module Refinery
module Objects
class Object < Refinery::Core::BaseModel
self.table_name = 'refinery_objects'
after_create :send_emails
#before_save { |record| record.location = Refinery::Objects::Util.provide_position(record.address) }
attr_accessible :title, :position, :address, :location, :distance, :plan, :description, :space, :plan, :floor, :parking, :parkingcost, :rentcost, :photo_id
acts_as_indexed :fields => [:title, :address, :distance, :plan, :description]
validates :title, :presence => true, :uniqueness => true
validates :rentcost, :address, :photo_id, :presence => true
belongs_to :photo, :class_name => '::Refinery::Image'
has_many_page_images
public
def parking
self[:parking] ? ::I18n.t('yes') : ::I18n.t('no')
end
private
def send_emails
Subscribers.all.each { |s| Refinery::Objects::NewObjectJob.perform_async(s.id, self.id) }
end
end
end
end
|
require "rails_helper"
RSpec.feature "visitor can view data for specific items", type: :feature do
context "as a visitor when I visit the show page" do
let!(:item) do
Item.create(title: "Brachiosaurus Scarf",
description: "An extra long scarf for all of those littlefoots in your life",
price: 230,
image: "img[src*='http://vignette1.wikia.nocookie.net/scarfheroes/images/e/e6/Royal-stewart-tartan-lambswool-scarf.jpg/revision/latest?cb=20150322230625']")
end
scenario "when a visitor is on an items show they see the items details" do
visit item_path(item)
within "#title" do
expect(page).to have_content("Brachiosaurus Scarf Details")
end
within "#item-thumbnail" do
expect(page).to have_css("img[src*='http://vignette1.wikia.nocookie.net/scarfheroes/images/e/e6/Royal-stewart-tartan-lambswool-scarf.jpg/revision/latest?cb=20150322230625']")
expect(page).to have_content("An extra long scarf for all of those
littlefoots in your life")
end
within ".price_and_quantity" do
expect(page).to have_content("230")
end
end
end
end
|
FactoryGirl.define do
factory :gladiator do
name 'Nanos'
age '31'
gender 'male'
end
end
FactoryGirl.define do
factory :amunition do
amunition_type "arms"
title "helmet"
description "bronze closed helmet"
association :gladiators#, :factory => :gladiator
end
end |
class AddFinishedToPlayers < ActiveRecord::Migration
def up
add_column :players, :finished_at, :datetime
Player.all.each do |player|
player.touch(:finished_at) if !player.has_rounds?
end
end
def down
remove_column :players, :finished_at
end
end
|
class Writing_tip
attr_reader :text
def initialize(text)
@text = text
end
end
end
|
=begin
#Location API
#Geolocation, Geocoding and Maps
OpenAPI spec version: 2.0.0
Generated by: https://openapi-generator.tech
OpenAPI Generator version: 3.3.4
=end
require 'uri'
module unwiredClient
class GEOLOCATIONApi
attr_accessor :api_client
def initialize(api_client = ApiClient.default)
@api_client = api_client
end
# Geolocation
# The Geolocation API helps developers locate IoT, M2M and other connected devices anywhere in the world without GPS. The device first sends the API data about which Cellular networks and WiFi networks it can see nearby. The API then uses Unwired Labs’ large datasets of Cell towers, WiFi networks backed by numerous algorithms to calculate and return the device’s location
# @param geolocation_schema
# @param [Hash] opts the optional parameters
# @return [Object]
def geolocation(geolocation_schema, opts = {})
data, _status_code, _headers = geolocation_with_http_info(geolocation_schema, opts)
data
end
# Geolocation
# The Geolocation API helps developers locate IoT, M2M and other connected devices anywhere in the world without GPS. The device first sends the API data about which Cellular networks and WiFi networks it can see nearby. The API then uses Unwired Labs’ large datasets of Cell towers, WiFi networks backed by numerous algorithms to calculate and return the device’s location
# @param geolocation_schema
# @param [Hash] opts the optional parameters
# @return [Array<(Object, Fixnum, Hash)>] Object data, response status code and response headers
def geolocation_with_http_info(geolocation_schema, opts = {})
if @api_client.config.debugging
@api_client.config.logger.debug 'Calling API: GEOLOCATIONApi.geolocation ...'
end
# verify the required parameter 'geolocation_schema' is set
if @api_client.config.client_side_validation && geolocation_schema.nil?
fail ArgumentError, "Missing the required parameter 'geolocation_schema' when calling GEOLOCATIONApi.geolocation"
end
# resource path
local_var_path = '/process.php'
# query parameters
query_params = {}
# header parameters
header_params = {}
# HTTP header 'Accept' (if needed)
header_params['Accept'] = @api_client.select_header_accept(['application/json'])
# HTTP header 'Content-Type'
header_params['Content-Type'] = @api_client.select_header_content_type(['application/json'])
# form parameters
form_params = {}
# http body (model)
post_body = @api_client.object_to_http_body(geolocation_schema)
auth_names = []
data, status_code, headers = @api_client.call_api(:POST, local_var_path,
:header_params => header_params,
:query_params => query_params,
:form_params => form_params,
:body => post_body,
:auth_names => auth_names,
:return_type => 'Object')
if @api_client.config.debugging
@api_client.config.logger.debug "API called: GEOLOCATIONApi#geolocation\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}"
end
return data, status_code, headers
end
end
end
|
class DomainMailer < ApplicationMailer
include Que::Mailer
def pending_delete_rejected_notification(domain_id, should_deliver)
@domain = Domain.find_by(id: domain_id)
return unless @domain
return if delivery_off?(@domain, should_deliver)
# no delivery off control, driggered by que, no epp request
if @domain.registrant_verification_token.blank?
logger.warn "EMAIL NOT DELIVERED: registrant_verification_token is missing for #{@domain.name}"
return
end
if @domain.registrant_verification_asked_at.blank?
logger.warn "EMAIL NOT DELIVERED: registrant_verification_asked_at is missing for #{@domain.name}"
return
end
return if whitelist_blocked?(@domain.registrant.email)
mail(to: format(@domain.registrant.email),
subject: "#{I18n.t(:pending_delete_rejected_notification_subject,
name: @domain.name)} [#{@domain.name}]")
end
def pending_delete_expired_notification(domain_id, should_deliver)
@domain = Domain.find_by(id: domain_id)
return unless @domain
return if delivery_off?(@domain, should_deliver)
# no delivery off control, driggered by cron, no epp request
return if whitelist_blocked?(@domain.registrant.email)
mail(to: format(@domain.registrant.email),
subject: "#{I18n.t(:pending_delete_expired_notification_subject,
name: @domain.name)} [#{@domain.name}]")
end
def delete_confirmation(domain_id, should_deliver)
@domain = Domain.find_by(id: domain_id)
return unless @domain
return if delivery_off?(@domain, should_deliver)
return if whitelist_blocked?(@domain.registrant.email)
mail(to: format(@domain.registrant.email),
subject: "#{I18n.t(:delete_confirmation_subject,
name: @domain.name)} [#{@domain.name}]")
end
end |
class MakeAmountsDefaultZero < ActiveRecord::Migration
def change
change_column :campaigns, :amount_donated, :integer, :default => 0, :null => false
change_column :payments, :amount_cents, :integer, :default => 0, :null => false
change_column :payments, :app_fee_cents, :integer, :default => 0, :null => false
change_column :payments, :wepay_fee_cents, :integer, :default => 0, :null => false
end
end
|
class CreateAddressBook < ActiveRecord::Migration[5.1]
def change
create_table :address_books do |t|
t.string :address
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
add_reference :address_books, :users, foreign_key: true
end
end
|
feature 'users profile page' do
context 'user has signed in and entred rounds and holes' do
scenario 'user visits profile page which displays stats', js: true do
sign_up
record_round
record_holes
click_link('Profile Page')
expect(current_path).to eq('/users/1')
expect(page).to have_content('First User Profile Page')
expect(page).to have_content('Current Handicap: 25')
expect(page).to have_content('28')
expect(page).to have_content('44')
end
end
end
|
class String
def is_anagram?(other)
self.chars.sort == other.chars.sort
end
end
p 'dog'.is_anagram?('god')
|
class LinksController < ApplicationController
before_action :authenticate_user!, only: :create
def new
@language = Language.find_by_slug(params[:language]) || not_found
@newLink = Link.new
end
def show
@link = Link.find(params[:id])
@newLink = Link.new
@language = @link.tag.language
render '/languages/show'
end
def create
@newLink = current_user.links.build(link_params)
@language = Language.find(link_params['language'].to_i)
if @newLink.save
Tag.create do |t|
t.link_id = @newLink.id
t.language_id = @language.id
end
flash[:new_link_id] = @newLink.id
redirect_to language_link_path(@newLink.tag.language, @newLink)
else
flash[:error] = @newLink.errors.full_messages.join(", ")
render 'new'
end
end
private
def link_params
params.require(:link).permit(:url, :description, :title, :level, :free, :language, :author)
end
end
|
module Capcoauth
module OAuth
class TTLCache
def self.user_id_for(access_token)
store.fetch(key_for(access_token))
end
def self.update(access_token, user_id)
store.write(key_for(access_token), user_id, expires_in: Capcoauth.configuration.token_verify_ttl)
end
def self.remove(access_token)
store.delete(key_for(access_token))
end
def self.key_for(access_token)
"capcoauth_token:#{access_token}"
end
def self.store
Capcoauth.configuration.cache_store
end
end
end
end
|
class Landmark < ApplicationRecord
include Mongoid::Document
include Mongoid::Timestamps
include Location
index_location
field :name, type: String
validates_presence_of :name
validates_presence_of_location
def self.center_loc
len = Landmark.all.count
return {lat: 35.6549, lng: 139.7373} if len == 0
Landmark.all.inject({lat: 0, lng: 0}) do |ave, l|
ave[:lat] += l.lat.to_f / len
ave[:lng] += l.lng.to_f / len
ave
end
end
end
|
class AddIntendedBeneficiariesToActivities < ActiveRecord::Migration[6.0]
def change
add_column :activities, :intended_beneficiaries, :string, array: true
end
end
|
# frozen_string_literal: true
require 'rails_helper'
require 'fixtures/test_hash_array'
RSpec.describe BusRouteImporter do
describe '.main' do
before { allow($stdout).to receive(:write).and_return(nil) }
describe 'for one row of data' do
let(:data) { TEST_HASH_ARRAY[0...1] }
it 'adds a rider, bus_routes, route_stops, and a bus_stop to the db' do
expect { described_class.main.call(data) }
.to change { Rider.count }
.by(1)
.and change { BusStop.count }
.by(1)
.and change { BusRoute.count }
.by(2)
.and change { RouteStop.count }
.by(2)
end
it 'sets associations between Rider, BusStop, and BusRoute' do
described_class.main.call(data)
stop = BusStop.first
route1, route2 = BusRoute.first(2)
route_stop1, route_stop2 = RouteStop.first(2)
rider = Rider.first
expect(stop.bus_routes).to include(route1, route2)
expect(route1.bus_stops).to include(stop)
expect(route2.bus_stops).to include(stop)
expect(BusStop.all).to include(route_stop1.bus_stop)
expect(BusRoute.all).to include(route_stop1.bus_route)
expect(BusStop.all).to include(route_stop2.bus_stop)
expect(BusRoute.all).to include(route_stop2.bus_route)
expect([rider.pickup_route_stop_id, rider.dropoff_route_stop_id])
.to match_array [route_stop1.id, route_stop2.id]
end
end
describe 'for many rows of data' do
let(:data) { TEST_HASH_ARRAY }
it 'adds riders, bus_stops, bus_routes, and route_stops to the db' do
expect { described_class.main.call(data) }
.to change { Rider.count }
.by(5)
.and change { BusStop.count }
.by(4)
.and change { BusRoute.count }
.by(6)
.and change { RouteStop.count }
.by(8)
end
end
describe 'for existing route stops' do
let(:data) do
[TEST_HASH_ARRAY[0],
TEST_HASH_ARRAY[0].merge(pickup_time: '5:00 PM')]
end
before do
described_class.main.call([data[0]])
end
it 'updates stop time' do
route = BusRoute.find_by(uuid: data[0][:pickup_route])
stop = BusStop.find_by(address: data[0][:pickup_bus_stop])
expect { described_class.main.call(data) }
.to change { RouteStop.find_by(bus_stop: stop, bus_route: route).stop_time.strftime('%I:%M %p') }
.from('12:26 PM')
.to('05:00 PM')
end
end
describe 'for existing riders' do
let(:data) do
[TEST_HASH_ARRAY[0],
TEST_HASH_ARRAY[0].merge(pickup_route: 'LLMB10MID')]
end
before do
described_class.main.call([data[0]])
end
it 'updates dropoff and pickup spots' do
expect { described_class.main.call(data) }
.to change {
Rider.find_by(
first_name: data[0][:first_name],
last_name: data[0][:last_name]
).pickup_route_stop
}
.and change { RouteStop.first.pickups.count }
.by(-1)
end
end
end
end
|
# Filters added to this controller apply to all controllers in the application.
# Likewise, all the methods added will be available for all controllers.
class ApplicationController < ActionController::Base
#require 'rss'
include SimpleCaptcha::ControllerHelpers
helper :all # include all helpers, all the time
include AuthenticatedSystem
before_filter :login_required
# See ActionController::RequestForgeryProtection for details
# Uncomment the :secret if you're not using the cookie session store
protect_from_forgery # :secret => '5ff9bae5c73b0c12f85fb9d0afda53fa'
# See ActionController::Base for details
# Uncomment this to filter the contents of submitted sensitive data parameters
# from your application log (in this case, all fields with names like "password").
# filter_parameter_logging :password
def create
@users = User.find(:all)
@user = User.new(params[:user])
success = @user && @user.save
if success && @user.errors.empty?
# Protects against session fixation attacks, causes request forgery
# protection if visitor resubmits an earlier form using back
# button.Uncomment if you understand the tradeoffs.
# reset session
redirect_to(users_path)
flash[:notice] = "Ny bruker lagt til!"
else
flash[:error] = "Hei. Vi kunne ikke lage kontoen. Det er viktig at du skriver riktig navn og epost og har et brukernavn mellom 3 og 40 karakterer."
render :action => 'index'
end
end
def instantiate_controller_and_action_names
@current_action = action_name
@current_controller = controller_name
end
def get_pages_for_tabs
@tabs = Page.find_main
end
def get_sub_tabs
@subtabs = Page.find_subpages
end
end
|
#!/usr/bin/env ruby
file_to_test = '<%= @file_to_test %>'
unless File.exists?(file_to_test)
$stderr.puts "Required file #{file_to_test} is missing."
exit 1
end
unless File.read(file_to_test).empty?
$stderr.puts "File #{file_to_test} is not empty, even though it should be."
exit 1
end
puts "All ok. File #{file_to_test} exists and is empty."
|
class Api::V1::BaseController < ApplicationController
protect_from_forgery with: :null_session,
if: Proc.new{|c| c.request.format.json?}
skip_before_action :verify_authenticity_token
before_action :destroy_session
before_action :authenticate!
attr_reader :current_client
rescue_from StandardError do |exception|
Rails.logger.warn "rescue_from #{exception.inspect}"
exception.backtrace.each{|f| Rails.logger.warn " #{f}"}
render json: {message: exception.message}, status: :internal_service_error
end
rescue_from ActiveRecord::RecordNotFound do |exception|
render json: {message: 'not found'}, status: :not_found
end
rescue_from CanCan::AccessDenied do |exception|
render json: {message: 'not found'}, status: :not_found
end
rescue_from InvalidState do |exception|
render json: {message: exception.message}, status: :conflict
end
def current_ability
@current_ability ||= ApiAbility.new(current_client)
end
private
def authenticate!
authenticate_token || render_unauthorized
end
def authenticate_token
authenticate_with_http_token do |token, options|
@current_client = Client.find_by(auth_token: token)
end
end
def render_unauthorized
self.headers['WWW-Authenticate'] = 'Token realm="Application"'
render json: {error: 'Bad credentials'}, status: :unauthorized
end
def destroy_session
request.session_options[:skip] = true
end
end
|
class Startup
attr_accessor :name, :investors
attr_reader :founder, :domain
@@all = []
@@all_domains = []
def initialize(name, founder, domain)
@name = name
@founder = founder
@domain = domain
@@all << self
@@all_domains << domain
end
def pivot(name, domain)
@name = name
@domain = domain
end
def self.all
@@all
end
def self.find_by_founder(founder)
@@all.detect {|x| x.founder == founder}
end
def self.domains
@@all_domains.uniq
end
def sign_contract(venture_capitalist, type_of_investment, amount_invested)
FundingRound.new(self, venture_capitalist, type_of_investment, amount_invested)
end
def num_funding_rounds
FundingRound.all.select { |round| round.startup == self }.count
end
def total_funds
startups_array = FundingRound.all.select { |x| x.startup == self }
startups_array.reduce(0) { |sum, round| sum + round.investment }
end
def investors
xyz = FundingRound.all.select { |x| x.startup == self }
xyz.map { |y| y.venture_capitalist }.uniq
end
def big_investors
investors = self.investors
# startups_array = FundingRound.all.select { |x| x.startup == self }
# investors = startups_array.map { | round | round.venture_capitalist }.uniq
investors.select { |y| y.total_worth > 1000000000 }
end
end
|
$is_Jekyll = false
begin
require "jekyll"
puts "testing cases using jekyll"
$is_Jekyll = true
rescue LoadError
require "liquid"
puts "testing cases using liquid"
end
Liquid::Template.error_mode = :strict
def isJekyll
$is_Jekyll
end
def assertEqual(expected, real)
if expected != real
raise "{#{real}} is not {#{expected}}"
end
end
def assertTrue(real)
raise "{#{real}} is not true" unless real
end
def assert_equal(expected, real)
assertEqual(expected, real)
end
def assertRaise(&block)
begin
yield block
rescue
return
end
raise 'expected exception'
end
def assert_nil(arg)
assert_equal nil, arg
end
if isJekyll
def jekyllContext(overrides = {})
config = Jekyll::Utils.deep_merge_hashes(Marshal.load(Marshal.dump(Jekyll::Configuration::DEFAULTS)), {
"destination" => "dest",
"incremental" => false,
"includes_dir" => "cases_variable_inside_import/_includes/",
"source" => ".",
"skip_config_files" => true,
"timezone" => "UTC",
"url" => "http://example.com",
"baseurl" => "/base",
"disable_disk_cache" => true,
})
config = Jekyll::Utils.deep_merge_hashes(config, overrides)
site = Jekyll::Site.new(Jekyll::Configuration.from(config))
Liquid::Context.new({ }, {}, :site => site)
end
class JekyllFilter
include Jekyll::Filters
attr_accessor :site, :context
def initialize(opts = {})
@context = jekyllContext(opts)
@site = @context.registers[:site]
end
end
def make_filter_mock(opts = {})
JekyllFilter.new(opts).tap do |f|
tz = f.site.config["timezone"]
Jekyll.set_timezone(tz) if tz
end
end
def render(data, source, context = {})
unless context.kind_of? Liquid::Context
context = jekyllContext({})
end
context.scopes[0] = data
Liquid::Template.parse(source, "strict_variables" => true).render!(context)
end
else
def render(data = {}, source)
Liquid::Template.parse(source, {:strict_variables => true}).render!(data)
end
end
|
class User < ActiveRecord::Base
#Includes:
#password, password_confirmation, and password_digest fields and authenticate method
has_secure_password
#Validators
validates :email, :presence => true, :uniqueness => true
end
|
class AddThumbnailToEssays < ActiveRecord::Migration
def change
add_attachment :essays, :thumbnail_image
end
end
|
# frozen_string_literal: true
class EmbuImage < ApplicationRecord
belongs_to :embu
belongs_to :image
validates :embu_id, :image_id, presence: true
validates :image_id, uniqueness: { scope: :embu_id }
end
|
require 'spec_helper'
describe PostsController, "routes" do
it "should route" do
{:get => "/"}.should route_to(:controller => "posts", :action => "index")
{:get => "/posts"}.should route_to(:controller => "posts", :action => "index")
{:post => "/posts"}.should route_to(:controller => "posts", :action => "create")
end
end
describe PostsController, "INDEX" do
it "should list" do
hornsby_scenario :post
get :index
assigns(:posts).should == [@post]
response.should be_success
end
end
describe PostsController, "NEW" do
it "should display creation form" do
hornsby_scenario
get :new
response.should be_success
end
end
describe PostsController, "CREATE" do
it "should display creation form" do
hornsby_scenario
post :create, :post => {
:title => 'title',
:body => 'body'
}
post = assigns(:post)
post.id.should_not == nil
post.title.should == 'title'
post.body.should == 'body'
post.ip_address.should == '0.0.0.0'
response.should redirect_to(root_path)
end
it "should render form again on validation failure" do
hornsby_scenario
post :create, :post => {
:title => '',
:body => 'body'
}
post = assigns(:post)
post.id.should == nil
response.should be_success
end
end
describe PostsController, "EDIT" do
it "should display edit form" do
hornsby_scenario :post
get :edit, :id => @post.id
response.should be_success
end
it "should fail because of different ip address" do
hornsby_scenario :post
@post.update(:ip_address => '0.0.0.1')
get :edit, :id => @post.id
response.code.should == "403"
end
it "should fail because of not existing post" do
hornsby_scenario
get :edit, :id => 1
response.code.should == "404"
end
end
describe PostsController, "UPDATE" do
it "should update" do
hornsby_scenario :post
put :update, :id => @post.id, :post => {
:title => 'h1',
:body => 'text'
}
response.should redirect_to(root_path)
@post.reload
@post.title.should == 'h1'
@post.body.should == 'text'
end
it "should render form again on validation failure" do
hornsby_scenario :post
put :update, :id => @post.id, :post => {
:title => '',
:body => 'text'
}
response.should be_success
end
end
|
class User < ActiveRecord::Base
has_many :games, foreign_key: 'player_1_id'
has_many :games, foreign_key: 'player_2_id'
validates :username, presence: true, uniqueness: true
validates :password, presence: true
end
|
class AddCharacterToMessage < ActiveRecord::Migration[6.1]
def up
change_table :messages do |t|
t.string :character
end
end
def down
remove_columns :messages, :character
end
end
|
require 'rails_helper'
describe API::V1::Users, type: :request do
NAMESPACE = '/api/v1'
let!(:user) { create(:user_admin) }
let!(:broker_user) { create(:user_broker) }
let!(:read_only_user) { create(:user) }
context "GET #{NAMESPACE}/users" do
it 'returns an array with all users' do
get "#{NAMESPACE}/users", nil, auth_header(user)
expect(response).to be_ok
expect(JSON.parse(response.body)['users'].size).to eq 3
end
end
context "GET #{NAMESPACE}/users/:id" do
context 'when user exist' do
it 'returns a specific user' do
get "#{NAMESPACE}/users/#{user.id}", nil, auth_header(user)
expect(response).to be_ok
expect(JSON.parse(response.body)['user']['id']).to eq(user.id)
end
end
context 'when user does not exist' do
it 'fails with 404 not found code' do
get "#{NAMESPACE}/users/#{user.id+9999}", nil, auth_header(user)
expect(response).to be_not_found
end
end
end
context "POST #{NAMESPACE}/users" do
let(:user_params) { attributes_for(:user) }
context 'when all required fields are present' do
it 'creates the user' do
post "#{NAMESPACE}/users", user_params, auth_header(user)
expect(response).to be_created
end
end
context 'when required fields are missing' do
before { user_params.delete(:name) }
it 'fails with 400 bad request code' do
post "#{NAMESPACE}/users", user_params, auth_header(user)
expect(response).to be_bad_request
end
end
context 'when a guest attempt to create' do
it 'fails with 403 forbidden code' do
post "#{NAMESPACE}/users", user_params, auth_header(read_only_user)
expect(response).to be_forbidden
end
end
context 'when a broker attempt to create' do
it 'fails with 403 forbidden code' do
post "#{NAMESPACE}/users", user_params, auth_header(broker_user)
expect(response).to be_forbidden
end
end
end
context "PUT #{NAMESPACE}/users/:id" do
let(:user_params) { { name: 'New User name' } }
context 'when at least one field is present' do
it 'updates that field' do
put "#{NAMESPACE}/users/#{user.id}", user_params, auth_header(user)
expect(response.status).to eq 204
expect(user.reload.name).to eq(user_params[:name])
end
end
context 'when it is an empty request' do
it 'fails with 400 bad request code' do
put "#{NAMESPACE}/users/#{user.id}", nil, auth_header(user)
expect(response).to be_bad_request
end
end
context 'when an user without permission attempt to update' do
it 'fails with 403 forbidden code' do
put "#{NAMESPACE}/users/#{user.id}", user_params, auth_header(read_only_user)
expect(response).to be_forbidden
end
end
context 'when an user attempts to update another user' do
it 'fails with 403 forbidden code' do
put "#{NAMESPACE}/users/#{user.id}", user_params, auth_header(broker_user)
expect(response).to be_forbidden
end
end
end
context "DELETE #{NAMESPACE}/users/:id" do
context 'when user is admin' do
it 'deletes the user from the system' do
delete "#{NAMESPACE}/users/#{broker_user.id}", nil, auth_header(user)
expect(response).to be_ok
expect{ broker_user.reload }.to raise_error(ActiveRecord::RecordNotFound)
end
end
context 'when user it deleting himself' do
it 'deletes the user from the system' do
delete "#{NAMESPACE}/users/#{broker_user.id}", nil, auth_header(broker_user)
expect(response).to be_ok
end
end
context 'when user is not admin an attempts to delete another user' do
it 'fails with 403 forbidden code' do
delete "#{NAMESPACE}/users/#{user.id}", nil, auth_header(broker_user)
expect(response).to be_forbidden
end
end
end
end
|
lib = File.expand_path("../lib", __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require "nasa-neo/version"
Gem::Specification.new do |s|
s.name = 'nasa-neo'
s.version = '1.5.4'
s.date = '2019-04-09'
s.summary = "This gem provides a wrapper for https://api.nasa.gov/api.html#NeoWS API"
s.description = "Retrieve information about Asteroids (Near Earth Objects) based on their closest approach date to Earth on any given day using the NASA NEO API. "
s.authors = ["James Sutherland"]
s.email = 'jrsutherland78@googlemail.com'
s.homepage = 'https://github.com/LondonJim/NASA-NEO-API-Wrapper'
s.license = 'MIT'
s.required_ruby_version = '>= 2.3.1'
s.metadata = { "homepage_uri" => "https://github.com/LondonJim/NASA-NEO-API-Wrapper",
"documentation_uri" => "https://www.rubydoc.info/github/LondonJim/NASA-NEO-API-Wrapper/master",
"changelog_uri" => "https://github.com/LondonJim/NASA-NEO-API-Wrapper/blob/master/CHANGELOG.md",
"source_code_uri" => "https://github.com/LondonJim/NASA-NEO-API-Wrapper"
}
s.files = Dir.chdir(File.expand_path('..', __FILE__)) do
`git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) }
end
s.bindir = 'bin'
s.require_paths = ['lib']
s.add_development_dependency 'bundler', '~> 2.0', '>= 2.0.1'
s.add_development_dependency 'rake', '~> 10.0'
s.add_development_dependency 'rspec', '~> 3.8'
s.add_development_dependency 'webmock', '~> 3.5', '>= 3.5.1'
end
|
require 'test_helper'
class HomeControllerTest < ActionController::TestCase
def setup
@controller = HomeController.new
@request = ActionController::TestRequest.new
@response = ActionController::TestResponse.new
end
def test_index
get :index
assert_response :success
assert_template 'home'
assert_not_nil assigns(:host)
assert_not_nil assigns(:host_port)
assert_not_nil assigns(:host_remote)
assert_not_nil assigns(:host_remoteip)
assert_not_nil assigns(:host_environment)
assert_select "title"
assert_select "div#main" do
assert_select "table#home-table"
end
assert_select "div#request-environment" do
assert_select "table#request-table"
end
end
end
|
class ApplicationController < ActionController::Base
protect_from_forgery with: :exception
layout :layout_by_resource
before_action :authenticate_user!, :configure_permitted_parameters, if: :devise_controller?
def after_sign_out_path_for(resource)
new_user_session_path
end
def after_sign_up_path_for(resource)
redirect_to new_user_registration_path
end
def after_update_path_for(resource)
redirect_to profile_path(resource)
flash[:notice] = "Account successfully updated"
end
rescue_from CanCan::AccessDenied do |exception|
Rails.logger.debug "Access Denied: #{exception.message}"
redirect_to request.referer
flash[:notice] = "Access Denied: You are not authorized to carry out this action"
end
protected
def set_attachment_name(name)
escaped = URI.encode(name)
response.headers['Content-Disposition'] = "attachment; filename*=UTF-8''#{escaped}"
end
def configure_permitted_parameters
devise_parameter_sanitizer.permit(:sign_up) do |u|
u.permit(:username, :first_name, :last_name, :email, :password)
end
devise_parameter_sanitizer.permit(:account_update) { |u| u.permit(:email, :password, :password_confirmation, :current_password, :first_name, :last_name)}
end
def layout_by_resource
if devise_controller? && resource_name == :user && controller_name == 'sessions' && action_name == "new"
"layout_blank"
elsif devise_controller? && resource_name == :user && controller_name == 'passwords'
"layout_blank"
elsif devise_controller? and user_signed_in?
"application"
else
"application"
end
end
end
|
# frozen_string_literal: true
module Fusuma
VERSION = '1.10.1'
end
|
class Admin::BaseController < ApplicationController
before_action :authenticate_user!
before_action :check_admin
protected
def check_admin
flash[:notice] = "Not enought rights to view this page"
redirect_to root_path unless current_user.admin?
end
end |
class Venue
include Mongoid::Document
include Mongoid::Timestamps::Created
include Mongoid::Timestamps::Updated
include Mongoid::Search
field :name, type: String
field :address_line_1, type: String
field :address_line_2, type: String, default: ->{ "" }
field :address_line_3, type: String, default: ->{ "" }
field :city, type: String
field :county, type: String, default: ->{ "" }
field :country, type: String
field :postcode, type: String
search_in :name, :address_line_1, :city
validates_each :name, :address_line_1, :city, :country, :postcode do |record, attr, value|
record.errors.add attr, "#{attr} cannot be empty" if value.blank?
record.errors.add attr, "#{attr} cannot have trailing white space" if has_trailing_space?(value)
end
private
def self.has_trailing_space?(value)
split = value.split(//)
return split.first.eql?(" ") || split.last.eql?(" ") ? true : false
end
def self.update_keywords
if Mongoid::Search.classes.blank?
Mongoid::Search::Log.log "No model to index keywords.\n"
else
Mongoid::Search.classes.each do |klass|
Mongoid::Search::Log.silent = ENV['SILENT']
Mongoid::Search::Log.log "\nIndexing documents for #{klass.name}:\n"
klass.index_keywords!
end
Mongoid::Search::Log.log "\n\nDone.\n"
end
end
end
|
class ChangeMailingTemplateToEmailTemplateId < ActiveRecord::Migration
def up
rename_column :mailings, :template, :email_template_id
change_column :mailings, :email_template_id, :integer
end
def down
change_column :mailings, :email_template_id, :string
rename_column :mailings, :email_template_id, :template
end
end
|
class Comment < ActiveRecord::Base
belongs_to :post
validates :name, presence: true
validates :body, uniqueness: true, presence: true
validate :name, length: { minimum: 3 }
validate :body, length: { minimum: 10 }
end
|
require 'net/http'
require 'digest/sha1'
require 'yaml'
require 'time'
def hash_request(data)
salt = '1bac7e3c3f67f2ccebc0a1529e9850cd97e23a24'
Digest::SHA1.hexdigest(data + salt)
end
|
# Define conversion functions
# By defining an idempotent conversion function like Point(), we can keep our
# public protocols flexible and convenient, while internally normalizing the inputs
# into a known, consistent type. Using the Ruby convention of naming the conversion
# function identically to the target class gives a strong hint to users about the
# semantics of the method. Combining a conversion function with conversion
# protocols like #to_ary or #to_point opens up the conversion function to further
# extension by client code.
module Graphics
module Conversions
module_function
def Point(*args)
case args.first
when Integer then Point.new(*args)
when String then Point.new(*args.first.split(':').map(&:to_i))
when ->(arg) { arg.respond_to?(:to_point) }
args.first.to_point
when ->(arg) { arg.respond_to?(:to_ary) }
Point.new(*args.first.to_ary)
else
raise TypeError, "Cannot convert #{args.inspect} to Point"
end
end
end
Point = Struct.new(:x, :y) do
def inspect
"#<Point: #{x}:#{y}>"
end
def to_point
self
end
end
Pair = Struct.new(:a, :b) do
def to_ary
[a, b]
end
end
class Flag
def initialize(x, y, flag_color)
@x, @y, @flag_color = x, y, flag_color
end
def to_point
Point.new(@x, @y)
end
end
end
include Graphics
include Graphics::Conversions
Point(Point.new(2, 3)) # => #<Point: 2:3>
Point([9, 7]) # => #<Point: 9:7>
Point(3, 5) # => #<Point: 3:5>
Point("8:10") # => #<Point: 8:10>
Point(Pair.new(23, 32)) # => #<Point: 23:32>
Point(Flag.new(42, 24, :red)) # => #<Point: 42:24>
def draw_rect(a, b)
a = Point(a)
b = Point(b)
# Draw the rect from point A to point B
end
|
class AddVisibilityIndexOnPosts < ActiveRecord::Migration
def change
add_index :posts, :visibility
end
end
|
class Api::V1::BusController < ApiController
before_action :authenticate_admin, only: [:create, :destroy, :update, :index]
before_action :check_role, only: [:create, :destroy, :update]
before_action :set_bus, only:[:destroy, :update, :show]
def create
bus_params = params.require(:bus).permit(
:code, :latitude, :longitude, :route_id)
route_id = bus_params[:route_id]
unless route_id.nil? or Route.find_by id: route_id
render status: :unprocessable_entity, json: {
error: "undefined route"}
return
end
bus = Bus.new(bus_params)
unless bus.valid?
render status: :unprocessable_entity, json: {
error: bus.errors.details,
message: bus.errors.full_messages}
return
end
if bus.save
render status: :created
else
render status: :bad_request
end
end
def update
bus_params = params.require(:bus).permit(
:latitude, :longitude, :route_id)
route_id = bus_params[:route_id]
unless route_id.nil? or Route.find_by id: route_id
render status: :unprocessable_entity, json: {
error: "undefined route"}
return
end
if @bus.update(bus_params)
render status: :ok
else
render status: :bad_request
end
end
def show
end
def index
@buses = Bus.all
end
def destroy
if @bus.delete
render status: :ok
else
render status: :bad_request
end
end
private
def check_role
@admin = current_admin
if @admin.nil? or @admin.role <'op_agent'
render status: :unauthorized
end
end
def set_bus
begin
@bus = Bus.find(params[:id])
rescue
render status: :not_found, json: {}
end
end
end
|
class Movie < Sequel::Model
one_to_many :bookings
def self.movies_by_day(day)
Movie.where(Sequel.lit("(days & #{day}) = #{day}")).all
end
def self.movies_by_id_and_day(id, day)
Movie.where(Sequel.lit("id = ? AND (days & #{day}) = #{day}", id)).all
end
end
|
class AddConfirmableToUsers < ActiveRecord::Migration
def change
add_column :users, :confirmation_token, :string
add_column :users, :confirmed_at, :datetime
add_column :users, :confirmation_sent_at, :datetime
add_column :users, :unconfirmed_email, :string
add_index :users, :confirmation_token, :unique => true
User.reset_column_information
User.all.each do |user|
user.confirmed_at = user.confirmation_sent_at = Time.now
user.save
end
end
end
|
require 'simplecov'
SimpleCov.start
ENV["RAILS_ENV"] ||= 'test'
require File.expand_path("../../config/environment", __FILE__)
require 'rspec/rails'
require 'rspec/autorun'
require 'vcr'
require 'webmock'
def user
User.create(
nickname: "brantwellman",
provider: "github",
name: "Brant Wellman",
email: "brantwellman@gmail.com",
uid: ENV['BW_UID'],
token: ENV['TOKEN'],
image: "https://avatars.githubusercontent.com/u/6422641?v=3"
)
end
RSpec.configure do |config|
config.expect_with :rspec do |expectations|
expectations.include_chain_clauses_in_custom_matcher_descriptions = true
end
config.mock_with :rspec do |mocks|
mocks.verify_partial_doubles = true
end
config.before :each do
OmniAuth.config.mock_auth[:github] = nil
OmniAuth.config.test_mode = true
OmniAuth.config.mock_auth[:github] = OmniAuth::AuthHash.new({ 'provider' => 'github',
'uid' => ENV['BW_UID'],
'credentials' => { 'token' => ENV['TOKEN'] },
'info' => {
'name' => 'Brant Wellman',
'email' => 'brantwellman@gmail.com',
'nickname' => 'brantwellman',
'image' => "https://avatars.githubusercontent.com/u/6422641?v=3"
}
})
end
end
|
require_relative "builders/insert_builder"
module Sqlbuilder
module Statements
class Insert
include Builders::InsertBuilder
def initialize(utils)
@utils = utils
@columns = []
@values_list = []
@records = []
end
def into(table)
@table = table
self
end
def columns(columns)
@columns = columns
self
end
def values(single_row_values)
@values_list << single_row_values
self
end
def record(key_value_hash)
@records << key_value_hash
self
end
def build
sql = "INSERT"
unless @records.empty?
@columns = @records.first.keys
@records.each {|record| @values_list << record.values }
end
sql << " #{build_into}"
sql << " #{build_columns}"
sql << " #{build_values}"
sql
end
end
end
end
|
=begin
https://www.codewars.com/kata/576bb71bbbcf0951d5000044
=end
# my solution
def count_positives_sum_negatives(lst)
count_positives = lst.select {|x| x > 0}.length
sum_negatives = lst.select {|x| x < 0}.inject(0, :+)
return lst.empty? ? [] : [count_positives, sum_negatives]
end |
class Definition
define_method(:initialize) do |word_type, definition|
@word_type = word_type
@definition = definition
end
define_method(:word_type) do
@word_type
end
define_method(:definition) do
@definition
end
end
|
# == Schema Information
#
# Table name: clients
#
# id :integer not null, primary key
# name :string(255)
# company :string(255)
# email :string(255)
# phone :string(255)
# address :string(255)
# suburb :string(255)
# state :string(255)
# postcode :string(255)
# created_at :datetime
# updated_at :datetime
# user_id :integer
# favourite :boolean default(FALSE)
# booked_items_count :integer default(0)
# jobs_count :integer default(0)
# notes :text
# exclude_from_emails :boolean default(FALSE)
# client_type :string(255)
# last_email_date :date
# email_history :text
# manual_followup :boolean
#
class Client < ActiveRecord::Base
has_many :jobs
has_many :booked_items, through: :jobs
belongs_to :user
before_save :capitalize_text
def capitalize_text
self.attributes.each do |name, value|
if value.kind_of? String
unless [""].include? name
self.send("#{name}=", value.upcase)
end
end
end
end
end
|
class TeamMember < ActiveRecord::Base
has_many :social_profiles
has_and_belongs_to_many :batches
has_attached_file :profile_pic, default_url: "/images/missing.png"
validates_attachment_content_type :profile_pic, content_type: /\Aimage\/.*\z/
def as_json(options)
TeamMemberSerializer.new(self).as_json(root: false)
end
end
|
# rubymine won't run 1.9 tests
require 'minitest/unit'
require File.expand_path(File.dirname(__FILE__) + "/../lib/simple_record")
require "yaml"
require 'right_aws'
require 'my_model'
require 'my_child_model'
def setup
@config = YAML::load(File.read('test-config.yml'))
puts 'akey=' + @config['amazon']['access_key']
puts 'skey=' + @config['amazon']['secret_key']
RightAws::ActiveSdb.establish_connection(@config['amazon']['access_key'], @config['amazon']['secret_key'], :port=>80, :protocol=>"http")
SimpleRecord::Base.set_domain_prefix("simplerecord_tests_")
end
def teardown
RightAws::ActiveSdb.close_connection()
end
def test_dates
mm = MyModel.new
mm.name = "Travis"
mm.age = 32
mm.cool = true
mm.created = DateTime.now - 10
mm.updated = DateTime.now
mm.birthday = Time.now - (3600 * 24 * 365 * 10)
puts 'before save=' + mm.inspect
mm.save
puts 'after save=' + mm.inspect
mms = MyModel.find(:all, :conditions => ["created > ?", DateTime.now - 1])
puts 'mms=' + mms.inspect
end
def test_date_comparisons
t = SimpleRecord::Base.pad_and_offset(Time.now)
puts t
dt = SimpleRecord::Base.pad_and_offset(DateTime.now)
puts dt
dt_tomorrow = SimpleRecord::Base.pad_and_offset(DateTime.now + 1)
puts 'compare=' + (t <=> dt).to_s
puts 'compare=' + (t <=> dt_tomorrow).to_s
dts = DateTime.parse(dt_tomorrow)
puts dts.to_s
ts = Time.parse(dt)
puts ts.to_s
end
setup
#test_dates
test_date_comparisons
teardown
|
require 'spec_helper'
describe T::Session do
context 'run' do
context 'with session' do
let( :session_name ){ 'my-sess' }
let( :session ){ described_class.new session_name }
it 'an empty session opens only one window' do
set_interface_expectations(
[:query, 'has-session', '-t', session_name],
[:command, 'source-file', File.join(ENV["HOME"], '.tmux.conf')],
[:command, 'new-session', '-d', '-s', session_name, '-n', 'sh'],
[:command, 'set-window-option', '-g', 'automatic-rename', 'off'],
[:command, 'send-keys', '-t', [session_name, 0].join(':'), "cd #{PROJECT_HOME}".inspect, 'C-m'],
[:command, 'attach-session', '-t', session_name]
)
session.run do
end
end
it 'and a new_window can be opened' do
set_interface_expectations(
[:query, 'has-session', '-t', session_name],
[:command, 'source-file', File.join(ENV["HOME"], '.tmux.conf')],
[:command, 'new-session', '-d', '-s', session_name, '-n', 'sh'],
[:command, 'set-window-option', '-g', 'automatic-rename', 'off'],
[:command, 'send-keys', '-t', [session_name, 0].join(':'), "cd #{PROJECT_HOME}".inspect, 'C-m'],
[:command, 'new-window', '-t', session_name, '-n', "'vi'"],
[:command, 'send-keys', '-t', [session_name, 1].join(':'), "cd #{PROJECT_HOME}".inspect, 'C-m'],
[:command, 'attach-session', '-t', session_name]
)
session.run do
new_window 'vi'
end
end
it 'can also send some keys' do
set_interface_expectations(
[:query, 'has-session', '-t', session_name],
[:command, 'source-file', File.join(ENV["HOME"], '.tmux.conf')],
[:command, 'new-session', '-d', '-s', session_name, '-n', 'sh'],
[:command, 'set-window-option', '-g', 'automatic-rename', 'off'],
[:command, 'send-keys', '-t', [session_name, 0].join(':'), "cd #{PROJECT_HOME}".inspect, 'C-m'],
[:command, 'new-window', '-t', session_name, '-n', "'vi'"],
[:command, 'send-keys', '-t', [session_name, 1].join(':'), "cd #{PROJECT_HOME}".inspect, 'C-m'],
[:command, 'send-keys', '-t', [session_name,1].join(':'), 'vi .'.inspect, 'C-m'],
[:command, 'send-keys', '-t', [session_name,1].join(':'), ':colorscheme morning'.inspect, 'C-m'],
[:command, 'attach-session', '-t', session_name]
)
session.run do
new_window 'vi' do
send_keys 'vi .'
send_keys ':colorscheme morning'
end
end
end
end # context 'with session'
end # context 'run'
end # describe T::Session
|
FactoryBot.define do
EXAMPLES_OF_AVAILABLE_COMPONENTS = [
{title: 'Title'},
{title: 'Choices'},
{title: 'Section'},
{title: 'Photo'},
{title: 'Date'},
{title: 'Address'},
{title: 'Text'},
{title: 'Signature'},
{title: 'Yes/No'}
]
factory :available_component_type, :class => CheckListEngine::AvailableComponentType do
title { Faker::Lorem.word + rand(10000).to_s }
has_photo { false }
end
end
|
module Smite
class Achievements < Smite::Object
def inspect
"#<Smite::Achievements '#{name}'>"
end
end
end |
class AppointmentComment
include Mongoid::Document
include Mongoid::Timestamps
embedded_in :appointment
belongs_to :user
field :comment
end |
EffectiveEmailTemplates.setup do |config|
# Configure Database Tables
config.email_templates_table_name = :email_templates
# Authorization Method
#
# This method is called by all controller actions with the appropriate action and resource
# If the method returns false, an Effective::AccessDenied Error will be raised (see README.md for complete info)
#
# Use via Proc (and with CanCan):
# config.authorization_method = Proc.new { |controller, action, resource| can?(action, resource) }
#
# Use via custom method:
# config.authorization_method = :my_authorization_method
#
# And then in your application_controller.rb:
#
# def my_authorization_method(action, resource)
# current_user.is?(:admin)
# end
#
# Or disable the check completely:
# config.authorization_method = false
config.authorization_method = Proc.new { |controller, action, resource| authorize!(action, resource) } # CanCanCan
# Layout Settings
# Configure the Layout per controller, or all at once
# config.layout = 'application' # All EffectiveEmailTemplates controllers will use this layout
config.layout = {
email_templates: 'application',
admin_email_templates: 'admin'
}
end
|
=begin
"Point Mutations"
Write a program that can calculate the Hamming distance between two DNA strands.
A mutation is simply a mistake that occurs during the creation or copying of a nucleic
acid, in particular DNA. Because nucleic acids are vital to cellular functions, mutations
tend to cause a ripple effect throughout the cell. Although mutations are technically mistakes,
a very rare mutation may equip the cell with a beneficial attribute. In fact, the macro effects
of evolution are attributable by the accumulated result of beneficial microscopic mutations over
many generations.
The simplest and most common type of nucleic acid mutation is a point mutation, which replaces
one base with another at a single nucleotide.
By counting the number of differences between two homologous DNA strands taken from different
genomes with a common ancestor, we get a measure of the minimum number of point mutations that
could have occurred on the evolutionary path between the two strands.
This is called the 'Hamming distance'
GAGCCTACTAACGGGAT
CATCGTAATGACGGCCT
^ ^ ^ ^ ^ ^^
The Hamming distance between these two DNA strands is 7.
The Hamming distance is only defined for sequences of equal length. If you have
two sequences of unequal length, you should compute the Hamming distance over the
shorter length.
=end
class DNA
def initialize(strand)
@strand = strand
end
def hamming_distance(other_strand)
shorter_size = @strand.size <= other_strand.size ? @strand.size : other_strand.size
distance = 0
for i in (0...shorter_size)
if @strand.chars[i] == other_strand.chars[i]
next
else
distance += 1
end
end
distance
end
end
|
#encoding:utf-8
module QiyuHelper
#
# 获取吃叫花鸡详情
#
def get_jiaohuaji_detail
re, user = validate_session_key(get_params(params, :session_key))
return unless re
recorder = JiaohuajiRecorder.get_recorders_of_today(user)
render_result(ResultCode::OK, recorder)
end
#
# 吃叫花鸡
#
def eat_jiaohuaji
re, user = validate_session_key(get_params(params, :session_key))
return unless re
type = params[:type]
if type.nil? || type.to_i < 0 || type.to_i > 2
return render_result(ResultCode::INVALID_PARAMETERS, {err_msg: 'invalid parameters'})
end
type = type.to_i
if JiaohuajiRecorder.eat(user, type)
render_result(ResultCode::OK, {})
else
render_result(ResultCode::ERROR, {})
end
end
#
# 获取当前的参拜记录
#
def get_canbai_recorders
re, user = validate_session_key(get_params(params, :session_key))
return unless re
render_result(ResultCode::OK, CanbaiRewardRecorder.get_recorder(user))
end
#
# 参拜接口
#
def canbai
re, user = validate_session_key(get_params(params, :session_key))
return unless re
recorder = CanbaiRewardRecorder.find_by_user_id(user.id)
if recorder.nil?
recorder = CanbaiRewardRecorder.new
recorder.user = user
recorder.save
end
re, goods = recorder.canbai
unless re
return render_result(ResultCode::ERROR, {err_msg: "error..."})
end
render_result(ResultCode::OK, {goods: goods})
end
end |
require "chef/resource/lwrp_base"
require "chef/provisioning/azure_driver/subscriptions"
class Chef
module Provisioning
module AzureDriver
class AzureResource < Chef::Resource::LWRPBase
def initialize(*args)
super
if run_context
@chef_environment = run_context.cheffish.current_environment
@chef_server = run_context.cheffish.current_chef_server
@driver = run_context.chef_provisioning.current_driver
end
config = run_context.chef_provisioning.config
scheme, account_id = driver.split(":", 2)
if account_id.nil? || account_id.empty?
subscription = Subscriptions.default_subscription(config)
config = Cheffish::MergedConfig.new({ azure_subscriptions: subscription }, config)
if !subscription
raise "Driver #{driver} did not specify a subscription ID, and no default subscription was found. Have you downloaded the Azure CLI and used `azure account download` and `azure account import` to set up Azure? Alternately, you can set azure_subscriptions to [ { subscription_id: '...', management_credentials: ... }] in your Chef configuration."
end
else
subscription_id = account_id || subscription[:subscription_id]
subscription = Subscriptions.get_subscription(config, subscription_id)
end
if !subscription
raise "Driver #{driver} has a subscription ID (#{subscription_id}), but the system has no credentials configured for it! If you have access to this subscription, you can use `azure account download` and `azure account import` in the Azure CLI to get the credentials, or set azure_subscriptions to [ { subscription_id: '...', management_credentials: ... }] in your Chef configuration."
else
Chef::Log.debug("Using subscription: #{subscription.inspect}")
end
Azure.configure do |azure|
azure.management_certificate = subscription[:management_certificate]
azure.subscription_id = subscription[:subscription_id]
azure.management_endpoint = subscription[:management_endpoint]
end
end
attribute :driver
attribute :chef_server, kind_of: Hash
attribute :managed_entry_store, kind_of: Chef::Provisioning::ManagedEntryStore,
lazy_default: proc { Chef::Provisioning::ChefManagedEntryStore.new(chef_server) }
attribute :subscription
end
end
end
end
|
class EventIndexByIdJob < ActiveJob::Base
queue_as :lagottino
def perform(options={})
Event.index_by_id(options)
end
end |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.