text stringlengths 10 2.61M |
|---|
class AddProcessingToUsers < ActiveRecord::Migration
def change
add_column :uploads, :dwc_processing, :boolean
end
end
|
When /^I visit "([^"]+)"$/ do |page|
visit(page)
end
Then /^I should be on "([^"]+)"$/ do |page|
current_url.should == page
end
Then /^Firebug should be active$/ do
evaluate_script('!!(window.console && (window.console.firebug || window.console.exception))').should be_true
end
|
module Enocean
module Esp3
class Rorg4BS < Radio
def self.rorg_code
0xa5
end
def self.create(data=[0,0,0,0], sender_id=[0xff,0xff,0xff,0xff], status = 0)
base_data = [rorg_code] + data + sender_id + [status]
return self.new(Enocean::Esp3::Radio.type_id, base_data)
end
def telegram_data
radio_data[0..3]
end
def eep_provided?
learn? && (radio_data.last & 0x80) == 0x80
end
def eep
if eep_provided?
data = radio_data.pack("C*").unpack("N").first
func = (data & 0xff000000) >> 26
type = (data & 0x03f80000) >> 19
manuf = (data & 0x0007ff00) >> 8
EepId.new [Rorg4BS.rorg_code, func, type, manuf]
end
end
end
class Rorg1BS < Radio
def self.rorg_code
0xd5
end
def self.create(data=0, sender_id=[0xff,0xff,0xff,0xff], status = 0)
base_data = [rorg_code] + [data] + sender_id + [status]
return self.new(Enocean::Esp3::Radio.type_id, base_data)
end
def telegram_data
radio_data.first
end
end
class RorgRPS < Rorg1BS
def self.rorg_code
0xf6
end
def learn?
false
end
end
class RorgVLD
def self.rorg_code
0xd2
end
# not implemented !
end
end
end
|
class CartsController < ApplicationController
def show
@staches = @cart.staches
end
end
|
class CreateMemoryComments < ActiveRecord::Migration[5.2]
def change
create_table :memory_comments do |t|
t.references :pet
t.references :memory
t.string :comment
t.timestamps
end
end
end
|
class AddUnmatchedToProjectMedias < ActiveRecord::Migration[6.1]
def change
add_column :project_medias, :unmatched, :integer, default: 0
add_index :project_medias, :unmatched
# add mapping for unmatched
index_alias = CheckElasticSearchModel.get_index_alias
client = $repository.client
options = {
index: index_alias,
body: {
properties: {
unmatched: { type: 'long' },
}
}
}
client.indices.put_mapping options
end
end
|
require 'pry'
class Day12
class Point3D
attr_accessor :x, :y, :z
def initialize(x = 0, y = 0, z = 0)
@x = x
@y = y
@z = z
end
def g(c1, c2)
case
when c1 == c2
0
when c1 > c2
-1
when c1 < c2
1
end
end
def gravity(other)
Point3D.new(g(x, other.x),
g(y, other.y),
g(z, other.z))
end
def +(other)
Point3D.new(x + other.x,
y + other.y,
z + other.z)
end
def sum
x.abs + y.abs + z.abs
end
def to_s
"x=#{x} y=#{y} z=#{z}"
end
def hash
[ x, y ,z ].hash
end
def to_a
[ x, y, z ]
end
end
EXAMPLE_ONE = [
Moon.new(-1, 0, 2),
Moon.new(2, -10, -7),
Moon.new(4, -8, 8),
Moon.new(3, 5, -1)
]
INPUT = [
Moon.new(-19, -4, 2),
Moon.new(-9, 8, -16),
Moon.new(-4, 5, -11),
Moon.new(1, 9, -13)
]
class Moon
attr_accessor :position, :velocity, :velocity_change
def initialize(x, y, z)
@position = Point3D.new(x, y, z)
@velocity = Point3D.new
@velocity_change = Point3D.new
end
def adjust_state
@velocity += @velocity_change
@position += @velocity
@velocity_change = Point3D.new(0, 0, 0)
end
def energy
@position.sum * @velocity.sum
end
def hash
[ @position, @velocity ].hash
end
def to_s
"pos=<#{position}>, vel=<#{velocity}>"
end
def to_a
@position.to_a + @velocity.to_a
end
end
def part1(moons = INPUT, turns = 1000)
(0...turns).each do |turn|
(0...4).each do |i|
((i + 1)...4).each do |j|
moons[i].velocity_change += (moons[i].position.gravity(moons[j].position))
moons[j].velocity_change += (moons[j].position.gravity(moons[i].position))
end
end
moons.each do |moon|
moon.adjust_state
#print_state(moons, turn)
end
end
moons.map {|moon| moon.energy}.sum
end
# does it have to return to first position before any others?
# would think no, so would have to check all
# if knew it would be first position we had to find
# 57,473,000 in something like 30 min
def part2(moons = INPUT, turns = 3000)
seen = {}
(0...turns).each do |turn|
(0...4).each do |i|
((i + 1)...4).each do |j|
moons[i].velocity_change += (moons[i].position.gravity(moons[j].position))
moons[j].velocity_change += (moons[j].position.gravity(moons[i].position))
end
end
moons.each do |moon|
moon.adjust_state
#print_state(moons, turn)
end
hash = moons.map(&:to_a).reduce(&:+).hash
if seen.has_key?(hash)
puts "seen in #{turn} turns"
return
end
seen[hash] = 1
#print_state(moons, turn)
if turn % 1000 == 0
puts "#{turn}"
end
end
end
def print_state(moons, turn)
puts "turn #{turn}"
moons.each do |moon|
moon.adjust_state
puts "#{moon}"
end
puts
end
end
|
require 'spec_helper'
require 'referencia'
describe Referencia do
before :each do
# Defino los valores que tomarán los atributos primero y luego le paso las variables al constructor del objeto Referencia
# Por conveniencia, el valor V es igual a Vacio, es decir: si un atributo tiene el valor V es como si no tuviera nada
autores = [ 'Dave Thomas', 'Andy Hunt', 'Chad Fowler' ]
titulo = 'Programming Ruby 1.9 & 2.0: The Pragmatic Programmers Guide'
serie = '(The Facets of Ruby)'
editorial = 'Pragmatic Bookshelf'
edicion = '4 edition'
fecha_publicacion = 'July 7, 2013'
isbn = [ 'ISBN-13: 978-1937785499', 'ISBN-10: 1937785491']
# Creo el objeto r1 de la clase Referencia
@r1 = Referencia.new(autores, titulo, serie, editorial, edicion, fecha_publicacion, isbn)
end
describe "# Creación correcta del objeto tipo Referencia" do
it "Debe crearse el objeto correctamente" do
@r1.should be_an_instance_of Referencia
end
end
describe "# Almacenamiento correcto de los atributos" do
it "Debe existir uno o más autores" do
@r1.get_autores.length.should_not be 0
end
it "Debe existir un título" do
@r1.get_titulo.should_not be 'V'
end
it "Debe existir una serie" do
@r1.get_serie.should_not be 'V'
end
it "Debe existir una editorial" do
@r1.get_serie.should_not be 'V'
end
it "Debe existir un número de edición" do
@r1.get_numero_edicion.should_not be 'V'
end
it "Debe existir una fecha de publicación" do
@r1.get_fecha_publicacion.should_not be 'V'
end
it "Debe existir uno o más números ISBN" do
@r1.get_isbn.length.should_not be 0
end
end
describe "# Existen los métodos de obtención de los atributos" do
it "Existe un método para obtener el listado de autores" do
@r1.respond_to?(:get_autores).should be true
end
it "Existe un método para obtener el título" do
@r1.respond_to?(:get_titulo).should be true
end
it "Existe un método para obtener la serie" do
@r1.respond_to?(:get_serie).should be true
end
it "Existe un método para obtener la editorial" do
@r1.respond_to?(:get_editorial).should be true
end
it "Existe un método para obtener el número de edición" do
@r1.respond_to?(:get_numero_edicion).should be true
end
it "Existe un método para obtener la fecha de publicación" do
@r1.respond_to?(:get_fecha_publicacion).should be true
end
it "Existe un método para obtener el listado de números ISBN" do
@r1.respond_to?(:get_isbn).should be true
end
it "Existe un método para obtener la referencia formateada" do
@r1.respond_to?(:get_referencia_formateada).should be true
end
end
end
|
class User < ActiveRecord::Base
class NotLoggedIn < StandardError;end
class PermissionDenied < StandardError;end
acts_as_authentic
attr_protected :points,:admin
attr_readonly :username
named_scope :better_than, lambda { |points| {:conditions =>["points > :p",{:p=>points}]}}
named_scope :worse_than, lambda { |points| {:conditions =>["points < :p",{:p=>points}] }}
named_scope :with_score, lambda { |points| {:conditions =>["points = :p", {:p=>points}] }}
named_scope :other_than, lambda {|user| {:conditions=>["id<>:id",{:id=>user.id}]}}
has_attached_file :photo,:styles => { :profile => "150x200>",
:thumb => "45x60>" },
:url => "/assets/users/:id/:style/:basename.:extension",
:path => ":rails_root/public/assets/users/:id/:style/:basename.:extension"
has_many :tiles, :dependent=>:nullify
has_many :pages
has_many :contributed_pages,:source=>:page,:through=>:tiles,:uniq=>true
def can_be_deleted?(user)
(user==self) || (user.try(:admin))
end
def can_be_updated?(user)
(user==self) || (user.try(:admin))
end
def recent_tiles(limit)
Tile.by_user(self).recent.all(:limit=>limit)
end
def point_distribution
tiles.with_points.count(:group=>:points)
end
def rank
User.better_than(points).count(:points,:distinct=>true)+1
end
def on_better_rank
User.with_score(User.better_than(points).minimum(:points))
end
def on_worse_rank
User.with_score(User.worse_than(points).maximum(:points))
end
def on_same_rank
User.with_score(points).other_than(self)
end
def displayed_name
shown? ? shown : username
end
def update_points!
self.points = tiles.sum(:points)
self.save!
end
end
|
Before("@user_agent") do |scenario|
@user_agent = true
@scenario = scenario
end
|
require 'attr_extras'
require 'json'
require 'uri'
require 'oauth2'
class CardSide
pattr_initialize :side_num, :side_type
def to_json(_)
{'sideNum' => side_num, 'sideType' => side_type}.to_json
end
end
class Card
pattr_initialize :card_number, :card_sides
def to_json(_)
{'cardNum' => card_number, 'cardSides' => card_sides}.to_json
end
end
class SideData
pattr_initialize :type, :link, :image
def to_json(_)
{'type' => type, 'linkId' => link, 'resourceUri' => image}.to_json
end
end
class Side
pattr_initialize :type, :number, :template, :data
def to_json(_)
{'type' => type, 'sideNum' => number, 'templateCode' => template, 'data' => [data]}.to_json
end
end
class Pack
pattr_initialize :version, :count, :product, :sides, :cards
def to_json
{'productVersion' => version, 'numCards' => count, 'productCode' => product, 'sides' => sides, 'cards' => cards}.to_json
end
end
side_data = Array.new
(1..10).each do |s|
(1..10).each do |t|
side_data << SideData.new('fixedImageData', 'background_template', "http:///x#{s}y#{t}.front.png")
end
end
(1..10).each do |s|
(1..10).each do |t|
side_data << SideData.new('fixedImageData', 'background_template', "http:///x#{s}y#{t}.back.png")
end
end
cards = Array.new(100)
(1..100).each do |c|
cards[c] = Card.new(c, [CardSide.new(c, 'image'), CardSide.new(100 + c, 'details')])
end
sides = Array.new(200)
(1..100).each do |s|
sides[s] = Side.new('image', s, 'minicard_full_image_landscape', side_data[s - 1])
sides[100 + s] = Side.new('details', 100 + s, 'minicard_full_details_image_landscape', side_data[100 + s - 1])
end
pack = Pack.new(1, 100, 'minicard', sides[1..200], cards[1..100])
pack_json = pack.to_json
#puts pack_json
client = OAuth2::Client.new(ENV['CLIENT_ID'], ENV['CLIENT_SECRET'], :site => 'http://www.moo.com/api/service/')
response = client.request(:post, '/api/service/?method=moo.pack.createPack&product=minicard', {:body => {'pack' => pack_json}})
puts response.body |
# Account Plans
#
Given /^(provider "[^"]*") allows to change account plan (directly|only with credit card|by request)?$/ do |provider,mode_string|
mode = change_plan_permission_to_sym(mode_string)
provider.set_change_account_plan_permission!(mode)
end
Given /^(provider "[^"]*") does not allow to change account plan$/ do |provider|
provider.set_change_account_plan_permission!(:none)
end
# Application Plans
#
Given /^(service "[^"]*") allows to change application plan (directly|only with credit card|by request|with credit card required)?$/ do |service,mode_string|
mode = change_plan_permission_to_sym(mode_string)
service.set_change_application_plan_permission!(mode)
end
Given(/^the provider service allows to change application plan (.*)$/) do |mode|
step %(service "#{@service.name}" allows to change application plan #{mode})
end
Given /^(service "[^"]*") does not allow to change application plan$/ do |service|
service.set_change_application_plan_permission!(:none)
end
Given /^(service "[^"]*") allows to choose plan on app creation$/ do |service|
service.set_change_plan_on_app_creation_permitted!(true)
end
# Service Plans
#
Given /^(provider "[^"]*") allows to change service plan (directly|only with credit card|by request)?$/ do |provider,mode_string|
mode = change_plan_permission_to_sym(mode_string)
provider.set_change_service_plan_permission!(mode)
end
|
class TimeSlot < ActiveRecord::Base
has_many :meetings
has_many :schedules, through: :meetings
def self.create_time_slots(schedule, options = {period: 60, start_time: 0, end_time: 1440,
start_day: 0, end_day: 7})
end_time = options[:end_time].to_i
start_time = options[:start_time].to_i
period = options[:period].to_i
start_day = options[:start_day].to_i
end_day = options[:end_day].to_i
periods_per_day = (end_time - start_time)/period
number_of_days = (end_day - start_day) + 1
number_of_days.times do |day|
periods_per_day.times do |num|
time_slot = TimeSlot.find_or_create_by day: start_day + day,
start_time: start_time + (num*period),
end_time: start_time + ((num + 1)*period)
schedule.time_slots << time_slot
end
end
end
end
|
class CreateEcmTournamentsSets < ActiveRecord::Migration
def change
create_table :ecm_tournaments_sets do |t|
t.integer :first_team_score
t.integer :second_team_score
# associations
t.references :ecm_tournaments_match
t.timestamps
end
add_index :ecm_tournaments_sets, :ecm_tournaments_match_id
end
end
|
class PostSerializer < ActiveModel::Serializer
attributes :id, :content, :user_id, :location_id, :location, :user, :date, :is_image, :post_comments, :day, :day_id
def date
return object.created_at.strftime("%I:%M %p ~ %m.%d.%Y")
end
def user
ActiveModel::SerializableResource.new(object.user, each_serializer: UserSerializer)
end
end
|
class CustomersController < ApplicationController
# GET /customers
# GET /customers.json
def index
@customers = Customer.includes([:invoices, :payments]).order(:name).all
render json: @customers
end
# GET /customers/1
# GET /customers/1.json
def show
@customer = Customer.includes(:invoices).find(params[:id].split(","))
render json: @customer
end
# POST /customers
# POST /customers.json
def create
@customer = Customer.new(customer_params)
if @customer.save
render json: @customer, status: :created, location: @customer
else
ap errors(@customer.errors)
render json: errors(@customer.errors), status: :unprocessable_entity
end
end
# PATCH/PUT /customers/1
# PATCH/PUT /customers/1.json
def update
@customer = Customer.find(params[:id])
if @customer.update(customer_params)
head :no_content
else
render json: @customer.errors, status: :unprocessable_entity
end
end
# DELETE /customers/1
# DELETE /customers/1.json
def destroy
@customer = Customer.find(params[:id])
@customer.destroy
head :no_content
end
protected
def customer_params
params.require(:customer).permit(
:name,
:address,
:city,
:region,
:postal_code,
:country,
:reference,
:status,
:email,
:phone,
:company
)
end
end
|
# this class models RAAC behaviour without trust (i.e. risk budgets and static intervals)
class Raac
def initialize
# superclasses can override this value, setting to 0 to disable risk budgeting
@budget_decrement = Parameters::BUDGET_DECREMENT
# track obligations
@active_obligations = Hash.new { |h,k| h[k] = [] }
end
# This function returns a pair of decision (true or false) and an obligation (can be "none")
def authorisation_decision(request, policy)
# compute the risk
risk = compute_risk(request, policy)
# get the mitigation strategy for the permission mentioned in the request
ms = Parameters::SENSITIVITY_TO_STRATEGIES[request[:sensitivity]]
obligation = :none
decision = false
fdomain = Parameters::REJECT_DOMAIN
# check for deny zone and check the user has enough budget for this owner
# (instant deny conditions)
if policy[request[:recipient]][0] != :deny &&
request[:requester].risk_budget[request[:owner]] > 0
# now check to see which risk domain the computed risk falls into
risk_domains(request).each do |did, domain|
if risk >= domain[0] && risk < domain[1] then
# set the obligation to whatever the mitigation strategy says for this risk domain
obligation = Parameters::MITIGATION_STRATEGIES[ms][did]
# if there was an obligation, decrease budget and add it to
# the active list for this agent
if obligation != :none then
add_obligation(request[:requester], obligation, request[:owner])
end
# if we are in the last domain then reject the request,
# otherwise accept (poss. with obligation)
if did == Parameters::REJECT_DOMAIN then
decision = false
else decision = true
end
# record this just for logging in the result
fdomain = did
end
end
end
# return lots of information
return {
decision: decision,
risk: risk,
obligation: obligation,
domain: fdomain,
strategy: ms,
requester: request[:requester].id,
recipient: request[:recipient].id,
source_zone: policy[request[:requester].id][0],
target_zone: policy[request[:recipient].id][0],
req_budget: request[:requester].risk_budget[request[:owner]]
}
end
def add_obligation(requester, obligation, owner)
@active_obligations[requester].push([obligation, owner])
requester.risk_budget[owner] -= @budget_decrement
end
def do_obligation(requester)
# if this requester has any open obligations, do one and restore
# budget
ob = @active_obligations[requester].pop
if ob != nil then requester.risk_budget[ob[1]] += @budget_decrement end
end
# failing an obligation is when it times out and it's not longer
# possible to get your budget back
def fail_obligation(requester)
@active_obligations[requester].pop
end
private
# This function is where everything happens - we take all the things
# which are happening in the domain and the context and compute a
# risk value - OUR CONTRIBUTION WILL GO HERE
def compute_risk(request, policy)
# how is this done in Liang's paper? there isn't risk computation
# - so we need to use some kindof approximation let's adopt a
# simple approach - trust is 0 for everyone so risk is always just
# the risk for the sensitivity label
Parameters::SENSITIVITY_TO_LOSS[request[:sensitivity]]
# 0 because to use the actual risk makes the system more cautious
# than our premissive mode, and since we don't punish bad
# blocking, it will always do better.
end
# get the risk domains, possibly adjusting for trust
def risk_domains(request)
Parameters::RISK_DOMAINS
end
end
|
require 'slop'
require 'traject'
require 'traject/indexer'
module Traject
# The class that executes for the Traject command line utility.
#
# Warning, does do things like exit entire program on error at present.
# You probably don't want to use this class for anything but an actual
# shell command line, if you want to execute indexing directly, just
# use the Traject::Indexer directly.
#
# A CommandLine object has a single persistent Indexer object it uses
class CommandLine
# orig_argv is original one passed in, remaining_argv is after destructive
# processing by slop, still has file args in it etc.
attr_accessor :orig_argv, :remaining_argv
attr_accessor :slop, :options
attr_accessor :indexer
attr_accessor :console
@@indexer_class_shortcuts = {
"basic" => "Traject::Indexer",
"marc" => "Traject::Indexer::MarcIndexer",
"xml" => "Traject::Indexer::NokogiriIndexer"
}
def initialize(argv=ARGV)
self.console = $stderr
self.orig_argv = argv.dup
self.slop = create_slop!(argv)
self.options = self.slop
self.remaining_argv = self.slop.arguments
end
# Returns true on success or false on failure; may also raise exceptions;
# may also exit program directly itself (yeah, could use some normalization)
def execute
if options[:version]
self.console.puts "traject version #{Traject::VERSION}"
return true
end
if options[:help]
self.console.puts slop.to_s
return true
end
(options[:load_path] || []).each do |path|
$LOAD_PATH << path unless $LOAD_PATH.include? path
end
arg_check!
self.indexer = initialize_indexer!
######
# SAFE TO LOG to indexer.logger starting here, after indexer is set up from conf files
# with logging config.
#####
indexer.logger.info("traject (#{Traject::VERSION}) executing with: `#{orig_argv.join(' ')}`")
# Okay, actual command process! All command_ methods should return true
# on success, or false on failure.
result =
case options[:command]
when "process"
(io, filename) = get_input_io(self.remaining_argv)
indexer.settings['command_line.filename'] = filename if filename
indexer.process(io)
when "marcout"
(io, filename) = get_input_io(self.remaining_argv)
indexer.settings['command_line.filename'] = filename if filename
command_marcout!(io)
when "commit"
command_commit!
else
raise ArgumentError.new("Unrecognized traject command: #{options[:command]}")
end
return result
rescue Exception => e
# Try to log unexpected exceptions if possible
indexer && indexer.logger && indexer.logger.fatal("Traject::CommandLine: Unexpected exception, terminating execution: #{Traject::Util.exception_to_log_message(e)}") rescue nil
raise e
end
def command_commit!
require 'open-uri'
raise ArgumentError.new("No solr.url setting provided") if indexer.settings['solr.url'].to_s.empty?
url = "#{indexer.settings['solr.url']}/update?commit=true"
indexer.logger.info("Sending commit to: #{url}")
indexer.logger.info( open(url).read )
return true
end
def command_marcout!(io)
require 'marc'
output_type = indexer.settings["marcout.type"].to_s
output_type = "binary" if output_type.empty?
output_arg = unless indexer.settings["output_file"].to_s.empty?
indexer.settings["output_file"]
else
$stdout
end
indexer.logger.info(" marcout writing type:#{output_type} to file:#{output_arg}")
case output_type
when "binary"
writer = MARC::Writer.new(output_arg)
allow_oversized = indexer.settings["marcout.allow_oversized"]
if allow_oversized
allow_oversized = (allow_oversized.to_s == "true")
writer.allow_oversized = allow_oversized
end
when "xml"
writer = MARC::XMLWriter.new(output_arg)
when "human"
writer = output_arg.kind_of?(String) ? File.open(output_arg, "w:binary") : output_arg
else
raise ArgumentError.new("traject marcout unrecognized marcout.type: #{output_type}")
end
reader = indexer.reader!(io)
reader.each do |record|
writer.write record
end
writer.close
return true
end
# @return (Array<#read>, String)
def get_input_io(argv)
filename = nil
io_arr = nil
if options[:stdin]
indexer.logger.info("Reading from standard input")
io_arr = [$stdin]
elsif argv.length == 0
io_arr = [File.open(File::NULL, 'r')]
indexer.logger.info("Warning, no file input given. Use command-line argument '--stdin' to use standard input ")
else
io_arr = argv.collect { |path| File.open(path, 'r') }
filename = argv.join(",")
indexer.logger.info "Reading from #{filename}"
end
return io_arr, filename
end
def load_configuration_files!(my_indexer, conf_files)
conf_files.each do |conf_path|
begin
my_indexer.load_config_file(conf_path)
rescue Errno::ENOENT, Errno::EACCES => e
self.console.puts "Could not read configuration file '#{conf_path}', exiting..."
exit 2
rescue Traject::Indexer::ConfigLoadError => e
self.console.puts "\n"
self.console.puts e.message
self.console.puts e.config_file_backtrace
self.console.puts "\n"
self.console.puts "Exiting..."
exit 3
end
end
end
def arg_check!
if options[:command] == "process" && (!options[:conf] || options[:conf].length == 0)
self.console.puts "Error: Missing required configuration file"
self.console.puts "Exiting..."
self.console.puts
self.console.puts self.slop.to_s
exit 2
end
end
def assemble_settings_hash(options)
settings = {}
# `-s key=value` command line
(options[:setting] || []).each do |setting_pair|
if m = /\A([^=]+)\=(.*)\Z/.match(setting_pair)
key, value = m[1], m[2]
settings[key] = value
else
self.console.puts "Unrecognized setting argument '#{setting_pair}':"
self.console.puts "Should be of format -s key=value"
exit 3
end
end
# other command line shortcuts for settings
if options[:debug]
settings["log.level"] = "debug"
end
if options[:'debug-mode']
require 'traject/debug_writer'
settings["writer_class_name"] = "Traject::DebugWriter"
settings["log.level"] = "debug"
settings["processing_thread_pool"] = 0
end
if options[:writer]
settings["writer_class_name"] = options[:writer]
end
if options[:reader]
settings["reader_class_name"] = options[:reader]
end
if options[:solr]
settings["solr.url"] = options[:solr]
end
if options[:marc_type]
settings["marc_source.type"] = options[:marc_type]
end
if options[:output_file]
settings["output_file"] = options[:output_file]
end
return settings
end
def create_slop!(argv)
options = Slop::Options.new do |o|
o.banner = "traject [options] -c configuration.rb [-c config2.rb] file.mrc"
o.on '-v', '--version', "print version information to stderr"
o.on '-d', '--debug', "Include debug log, -s log.level=debug"
o.on '-h', '--help', "print usage information to stderr"
o.array '-c', '--conf', 'configuration file path (repeatable)', :delimiter => nil
o.string "-i", '--indexer', "Traject indexer class name or shortcut", :default => "marc"
o.array "-s", "--setting", "settings: `-s key=value` (repeatable)", :delimiter => nil
o.string "-r", "--reader", "Set reader class, shortcut for -s reader_class_name="
o.string "-o", "--output_file", "output file for Writer classes that write to files"
o.string "-w", "--writer", "Set writer class, shortcut for -s writer_class_name="
o.string "-u", "--solr", "Set solr url, shortcut for -s solr.url="
o.string "-t", "--marc_type", "xml, json or binary. shortcut for -s marc_source.type="
o.array "-I", "--load_path", "append paths to ruby $LOAD_PATH", :delimiter => ":"
o.string "-x", "--command", "alternate traject command: process (default); marcout; commit", :default => "process"
o.on "--stdin", "read input from stdin"
o.on "--debug-mode", "debug logging, single threaded, output human readable hashes"
end
options.parse(argv)
rescue Slop::Error => e
self.console.puts "Error: #{e.message}"
self.console.puts "Exiting..."
self.console.puts
self.console.puts options.to_s
exit 1
end
def initialize_indexer!
indexer_class_name = @@indexer_class_shortcuts[options[:indexer]] || options[:indexer]
klass = Traject::Indexer.qualified_const_get(indexer_class_name)
indexer = klass.new self.assemble_settings_hash(self.options)
load_configuration_files!(indexer, options[:conf])
return indexer
end
end
end
|
require 'rails_helper'
RSpec.describe TradingStrategyService do
let(:user) {
User.create!(
email: 'foo@bar.com',
password: 'abcdabcd',
huobi_access_key: 'oo',
huobi_secret_key: 'ooo',
trader_id: trader.id
)
}
let(:trader) {
Trader.create!(webhook_token: 'oo', email: 'a@b.com', password: 'oooppp')
}
let(:exchange) { Exchange::Huobi.new(user, 'ETH') }
subject (:service) {
TradingStrategyService.new(trader: trader, exchange: exchange)
}
context 'tier strategy' do
it 'works' do
stub_user_history_with_loss
strategy_config = service.send(:strategy_config)
expect(strategy_config.name).to eq('tier')
expect(exchange.has_history?).to eq(true)
expect(exchange.last_order_profit?).to eq(false)
expect(exchange.continuous_fail_times).to eq(4)
expect(service.send(:open_order_percentage)).to eq(0.005.to_d * 5)
end
it 'last order has profit' do
stub_user_history
strategy_config = service.send(:strategy_config)
expect(strategy_config.name).to eq('tier')
expect(exchange.has_history?).to eq(true)
expect(exchange.last_order_profit?).to eq(true)
expect(service.send(:open_order_percentage)).to eq(0.005.to_d)
end
it 'reset to default' do
stub_user_history_with_loss
TradingStrategy.create!(trader_id: trader.id, name: 'tier', max_consecutive_fail_times: 4)
strategy_config = service.send(:strategy_config)
expect(strategy_config.name).to eq('tier')
expect(exchange.has_history?).to eq(true)
expect(exchange.last_order_profit?).to eq(false)
expect(exchange.continuous_fail_times).to eq(4)
expect(service.send(:open_order_percentage)).to eq(0.005.to_d)
end
end
context 'constant strategy' do
it 'reset to default' do
stub_user_history_with_loss
TradingStrategy.create!(trader_id: trader.id, name: 'constant', max_consecutive_fail_times: 3)
strategy_config = service.send(:strategy_config)
expect(strategy_config.name).to eq('constant')
expect(service.send(:open_order_percentage)).to eq(0.005.to_d)
end
end
end
|
class ApplicationController < ActionController::Base
include MicropostsHelper
before_action :configure_permitted_parameters, if: :devise_controller?
before_action :set_search_valiables
#
# 記事検索、ユーザー検索の初期設定
# @param [Array] post_search_result_count 記事検索結果件数を求める際に対象とする配列
# @param [Array] post_search_result 記事検索結果
# @param [Array] user_search_result ユーザー検索結果
#
def set_search_valiables
@post_search_key = Micropost.ransack(params[:q])
@post_search_result_count = @post_search_key.result(distinct: true)
@post_search_result = @post_search_key.result(distinct: true).page(params[:page])
@user_search_key = User.ransack(params[:q])
@user_search_result = @user_search_key.result(distinct: true).page(params[:page])
end
protected
#
# 新規登録、ログイン後のリダイレクト先を設定
#
def after_sign_in_path_for(_resource)
current_user
end
def configure_permitted_parameters
devise_parameter_sanitizer.permit(:sign_up, keys: [:name])
devise_parameter_sanitizer.permit(:sign_up, keys: [:avatar])
devise_parameter_sanitizer.permit(:account_update, keys: [:name])
devise_parameter_sanitizer.permit(:account_update, keys: [:avatar])
devise_parameter_sanitizer.permit(:account_update, keys: [:remove_avatar])
end
end
|
class ImagesController < UIViewController
include BW::KVO
# 画像のURL(NSURL)の入った配列
attr_accessor :image_urls, :current_page, :current_thumbnail_page, :parent
LOADING_IMAGE = UIImage.imageNamed('loading.png')
ERROR_IMAGE = UIImage.imageNamed('error.png')
RETRY_COUNT = 2
RECYCLE_BUFFER = 2
def init
if super
@image_queue = NSOperationQueue.new
@processing = []
@image_cache = NSCache.new.tap do |c|
c.name = 'images'
c.countLimit = 16
end
@current_page = 0
@visible_pages = []
@current_thumbnail_page = 0
@visible_thumbnail_pages = []
end
self
end
def loadView
self.view = UIView.new.tap do |v|
v.backgroundColor = UIColor.darkGrayColor
end
@stage = UIScrollView.alloc.initWithFrame([[0, 0], [320, 460]]).tap do |v|
v.pagingEnabled = true
v.showsVerticalScrollIndicator = false
v.showsHorizontalScrollIndicator = false
v.delegate = self
v.tag = 1
double_tap = UITapGestureRecognizer.new.tap do |g|
g.numberOfTapsRequired = 2
end
v.addGestureRecognizer(double_tap)
single_tap = UITapGestureRecognizer.alloc.initWithTarget(
self, action:'toggle_hud:').tap do |g|
g.requireGestureRecognizerToFail(double_tap)
end
v.addGestureRecognizer(single_tap)
end
view.addSubview(@stage)
@thumbnails = UIScrollView.alloc.initWithFrame([[0, 411], [320, 49]]).tap do |v|
v.pagingEnabled = true
v.showsVerticalScrollIndicator = false
v.showsHorizontalScrollIndicator = false
v.backgroundColor = UIColor.blackColor
v.alpha = 0.6
v.delegate = self
v.tag = 2
end
view.addSubview(@thumbnails)
@close_button = UIButton.buttonWithType(UIButtonTypeRoundedRect).tap do |b|
b.setTitle('閉じる', forState:UIControlStateNormal)
b.frame = [[10, 374], [60, 30]]
b.alpha = 0.6
b.addTarget(self, action:'close', forControlEvents:UIControlEventTouchUpInside)
end
view.addSubview(@close_button)
end
def dealloc
p "ImagesController dealloc #{self}"
clear_cached_images
p @visible_pages.map {|page| "#{page}: #{page.retainCount}"}.join(", ")
p @visible_thumbnail_pages.map {|page| "#{page}: #{page.retainCount}"}.join(", ")
super
end
def close
@parent.close_images(self)
end
def toggle_hud(gesture)
if @thumbnails.alpha > 0
UIView.animateWithDuration(0.2,
animations:lambda {
@thumbnails.alpha = 0
@close_button.alpha = 0
}
)
else
@thumbnails.alpha = 0.6
@close_button.alpha = 0.6
end
end
def viewWillAppear(animated)
super
@processing = []
AFNetworkActivityIndicatorManager.sharedManager.enabled = true
observe(self, 'current_page') do |old_index, new_index|
deselect(old_index) unless old_index.nil?
load_page
end
observe(self, 'current_thumbnail_page') do |old_index, new_index|
load_thumbnail_page
end
# サムネイルのタップ
@thumbnail_tap_observer = NSNotificationCenter.defaultCenter.addObserverForName('ThumbnailTapped', object:nil, queue:NSOperationQueue.mainQueue, usingBlock:lambda {|notif|
thumb = notif.object
image_index = notif.userInfo[:image_index]
index = thumb.index*4 + image_index
@stage.setContentOffset([index*320, 0], animated:true)
self.current_page = index
thumb.select_image(image_index)
})
# 画像の取得完了
@image_fetched_observer = NSNotificationCenter.defaultCenter.addObserver(self, selector:'image_fetched:', name:'ImageFetched', object:nil)
setup_pages
end
def viewDidDisappear(animated)
super
@image_queue.cancelAllOperations
unobserve_all
[@thumbnail_tap_observer, @image_fetched_observer].each do |observer|
NSNotificationCenter.defaultCenter.removeObserver(observer)
end
AFNetworkActivityIndicatorManager.sharedManager.enabled = false
p "================ ImagesController#retainCount: #{self.retainCount} ================"
end
def didReceiveMemoryWarning
super
p 'Memory Warning!! on ImagesController'
@image_cache.removeAllObjects
end
def scrollViewDidEndDragging(scrollView, willDecelerate:decelerate)
end_scroll(scrollView.tag) unless decelerate
end
def scrollViewDidEndDecelerating(scrollView)
end_scroll(scrollView.tag)
end
def scrollViewDidEndScrollingAnimation(scrollView)
# end_scroll
# これが発生するときはscrollViewDidEndDeceleratingも発生しているので
# ここでは呼ばなくてOK
end
private
def setup_pages
@pages_count = @image_urls.count
@stage.contentSize = [320*@pages_count, 460]
@thumbnails.contentSize = [320*(@pages_count/4.0).ceil, 40]
# 一番左に戻す
@stage.setContentOffset([0, 0], animated:false)
@thumbnails.setContentOffset([0, 0], animated:false)
self.current_page = 0
self.current_thumbnail_page = 0
end
def end_scroll(tag)
if tag == 1
end_stage_scroll
else
end_thumbnail_scroll
end
end
def end_stage_scroll
self.current_page = (@stage.contentOffset.x/320.0).ceil
self.current_thumbnail_page = @current_page/4
end
def end_thumbnail_scroll
self.current_thumbnail_page = (@thumbnails.contentOffset.x/320.0).ceil
end
def load_page
p "before: " + @visible_pages.map {|page| "#{page}: #{page.retainCount}"}.join(", ")
recycled_pages = []
# 不必要になったimage_scroll_viewを取り除く
@visible_pages.each do |page|
if page.index < @current_page-RECYCLE_BUFFER || page.index > @current_page+RECYCLE_BUFFER
recycled_pages << page
page.removeFromSuperview
end
end
@visible_pages.delete_if {|page| recycled_pages.include?(page)}
# 現在のページ + 前後のページを表示する
# ページがリサイクル出来ない場合は新しく作る
(@current_page-RECYCLE_BUFFER).upto(@current_page+RECYCLE_BUFFER) do |index|
next if index < 0 || index >= @pages_count
unless @visible_pages.any? {|pg| pg.index == index}
page_frame = [[index * 320, 0], @stage.frame.size]
page = recycled_pages.pop.tap {|v|
unless v.nil?
v.frame = page_frame
end
} || ImageScrollView.alloc.initWithFrame(page_frame)
@visible_pages << page
page.index = index
load_image_for_page(page, @image_urls[index])
@stage.addSubview(page)
end
end
p "after: " + @visible_pages.map {|page| "#{page}: #{page.retainCount}"}.join(", ")
# サムネイルの方もスクロールさせる
@thumbnails.setContentOffset([@current_page/4*320, 0], animated:true)
end
def load_thumbnail_page
p "before: " + @visible_thumbnail_pages.map {|page| "#{page}: #{page.retainCount}"}.join(", ")
recycled_thumbnail_pages = []
@visible_thumbnail_pages.each do |page|
if page.index < @current_thumbnail_page-RECYCLE_BUFFER || page.index > @current_thumbnail_page + RECYCLE_BUFFER
recycled_thumbnail_pages << page
page.removeFromSuperview
end
end
@visible_thumbnail_pages.delete_if {|page| recycled_thumbnail_pages.include?(page)}
(@current_thumbnail_page-RECYCLE_BUFFER).upto(@current_thumbnail_page+RECYCLE_BUFFER) do |index|
next if index < 0 || index >= (@pages_count / 4.0).ceil
unless @visible_thumbnail_pages.any? {|pg| pg.index == index}
page_frame = [[index * 320, 0], @thumbnails.frame.size]
page = recycled_thumbnail_pages.pop.tap {|v|
unless v.nil?
v.frame = page_frame
end
} || ThumbnailsView.alloc.initWithFrame(page_frame)
@visible_thumbnail_pages << page
page.index = index
load_images_for_thumbnails(page, @image_urls[index*4, 4])
@thumbnails.addSubview(page)
end
end
# 選択されている画像
if thumb_page = @visible_thumbnail_pages.detect {|page| page.index == @current_page/4 }
image_index = @current_page % 4
thumb_page.select_image(image_index)
end
p "after: " + @visible_thumbnail_pages.map {|page| "#{page}: #{page.retainCount}"}.join(", ")
end
def deselect(index)
# 1. 表示していた画像のズームを戻す
if page = @visible_pages.detect {|page| page.index == index }
page.zoomScale = page.minimumZoomScale
end
# 2. サムネイルの選択状態を解除
if thumb_page = @visible_thumbnail_pages.detect {|page| page.index == index/4}
thumb_page.deselect_image(index%4)
end
end
def load_image_for_page(page, url)
page.display_image(LOADING_IMAGE)
add_image_request_queue(page.index, url)
end
def load_images_for_thumbnails(thumbnails_view, urls)
# まずはサムネイルを全部クリア
thumbnails_view.remove_images
# サムネイル画像を取得
urls.each_with_index do |url, image_index|
index = thumbnails_view.index * 4 + image_index
thumbnails_view.display_image_with_index(LOADING_IMAGE, image_index)
add_image_request_queue(index, url)
end
end
def add_image_request_queue(index, url, retried = 0)
# ファイル名としても使うのでMD5する
key = key_for_url(url)
if cached_image = cached_image_for_key(key)
reload_image(cached_image, index)
elsif !@processing.include?(key)
@processing << key
req = NSURLRequest.requestWithURL(url,
cachePolicy:NSURLRequestReturnCacheDataElseLoad,
timeoutInterval:60)
opr = AFImageRequestOperation.imageRequestOperationWithRequest(req,
imageProcessingBlock:lambda{|image| image},
cacheName:nil,
success:lambda {|req, res, image|
@processing.delete key
@image_cache.setObject(image, forKey:key)
NSNotificationCenter.defaultCenter.postNotificationName('ImageFetched', object:image, userInfo:{index: index, key: key})
},
failure:lambda {|req, res, error|
log_error error
@processing.delete key
# RETRY_COUNT分繰り返す
if retried <= RETRY_COUNT
App.run_after(1.0) { add_image_request_queue(index, url, retried + 1) }
else
@image_cache.setObject(ERROR_IMAGE, forKey:key)
# エラーの画像を保存する必要は無い
reload_image(ERROR_IMAGE, index)
end
})
@image_queue.addOperation(opr)
end
end
def cached_image_for_key(key)
if cached_image = (@image_cache.objectForKey(key) || UIImage.imageWithContentsOfFile(cache_path_for_key(key)))
cached_image
else
nil
end
end
def key_for_url(url)
NSData.MD5HexDigest(
url.absoluteString.dataUsingEncoding(NSUTF8StringEncoding))
end
def file_manager
NSFileManager.defaultManager
end
def cache_dir
paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, true)
paths[0]
end
def clear_cached_images
images_dir = cache_dir.stringByAppendingPathComponent("images")
err_ptr = Pointer.new(:object)
file_manager.removeItemAtPath(images_dir, error:err_ptr)
error = err_ptr[0]
raise error if error
end
def cache_path_for_key(key)
# 画像保存のディレクトリを作る
# 数が多くなりそうなので分ける
# 頭2文字をディレクトリ名とする
path = cache_dir.stringByAppendingPathComponent("images/#{key[0, 2]}")
unless file_manager.fileExistsAtPath(path)
err_ptr = Pointer.new(:object)
file_manager.createDirectoryAtPath(path, withIntermediateDirectories:true, attributes:nil, error:err_ptr)
error = err_ptr[0]
raise error if error
end
path.stringByAppendingPathComponent(key)
end
def image_fetched(notification)
image = notification.object
index = notification.userInfo[:index]
key = notification.userInfo[:key] # ファイル名としても使う
# ファイルをローカルに保存
# data = UIImagePNGRepresentation(image)
data = UIImageJPEGRepresentation(image, 0.7)
if file_manager.createFileAtPath(cache_path_for_key(key), contents:data, attributes:nil)
reload_image(image, index)
else
# 保存に失敗
p "Error saving image..."
reload_image(ERROR_IMAGE, index)
end
end
def reload_image(image, index)
# @stageの画像更新
if page = @visible_pages.detect {|page| page.index == index }
page.display_image(image)
end
# @thumbnailsの画像更新
if page = @visible_thumbnail_pages.detect {|page| page.index == index/4 }
page.display_image_with_index(image, index%4)
# サムネイルを選択状態に
page.select_image(index%4) if @current_page == index
page.setNeedsDisplay
end
end
end |
class Participation < ApplicationRecord
require 'stripe'
belongs_to :participant
belongs_to :study
belongs_to :timeslot
has_many :participation_requirements
before_create :ensure_unique
# Filterrific config
filterrific(
default_filter_params: { sorted_by: 'created_at_asc' },
available_filters: [
:sorted_by
]
)
scope :sorted_by, lambda { |sort_option|
direction = sort_option =~ /desc$/ ? 'desc' : 'asc'
case sort_option.to_s
when /^created_at_/
order("participations.created_at #{direction}")
else
raise(ArgumentError, "Invalid sort option: #{sort_option.inspect}")
end
}
def send_email_to_say_accepted(study_id)
p "Accepted: #{accepted}"
p "participation_id = #{id}"
NotificationMailer.send_accepted_email(id, study_id).deliver_now
end
def pay_in_full
return unless participant.participant_attribute.managed_account_id
begin
Stripe::Transfer.create({
amount: study.reward_per_participant_pennies,
currency: 'gbp',
destination: participant.participant_attribute.managed_account_id,
metadata: { participation_id: id }
})
self.paid = true
save
rescue Stripe::RateLimitError => e
# Too many requests made to the API too quickly
p e
rescue Stripe::InvalidRequestError => e
# Invalid parameters were supplied to Stripe's API
p e
rescue Stripe::AuthenticationError => e
# Authentication with Stripe's API failed
# (maybe you changed API keys recently)
p e
rescue Stripe::APIConnectionError => e
# Network communication with Stripe failed
p e
rescue Stripe::StripeError => e
# Display a very generic error to the user, and maybe send
# yourself an email
p e
rescue => e
# Something else happened, completely unrelated to Stripe
p e
end
end
def rated
Ratings.where(study_id: study_id, user_being_rated_id: participant_id).any?
end
protected
def ensure_unique
# Return true if there are no other participations with both the same study
# and the same participant
!Participation.where(participant: self.participant, study: self.study).any?
end
end
|
# t.integer "server_id", null: false
# t.string "nickname", null: false
# t.string "hostname", default: "ricer.gizmore.org", null: false
# t.string "username", default: "Ricer", null: false
# t.string "realname", default: "Ricer IRC Bot", null: false
# t.string "password"
# t.datetime "created_at"
# t.datetime "updated_at"
module Ricer::Irc
class ServerNick < ActiveRecord::Base
scope :sorted, -> { order('server_nicks.updated_at DESC') }
belongs_to :server, :class_name => Server.name
def name
next_nickname
end
def next_nickname
self.nickname + (@cycle||'')
end
def next_cycle(cycle)
@cycle = cycle
end
def reset_cycle
next_cycle('')
end
def can_authenticate?
(self.password != nil) && (@cycle.nil? || @cycle.empty?)
end
end
end
|
class UrlSanatizator < Callable
PROTOCOL_REGEXP = /(https?:\/\/)|(www\.)/
def initialize(url:)
@dirty_url = url
end
def call
return nil if @dirty_url.nil?
sanitanize()
end
private
def sanitanize
local_url = @dirty_url.strip
local_url = @dirty_url.downcase.gsub(PROTOCOL_REGEXP, '')
local_url.slice!(-1) if local_url[-1]
"http://#{local_url}"
end
end
|
# fast version
def simplify_fraction(numerator, denominator, result)
greatest_common_divsor = gcd(numerator, denominator)
result[0] = numerator / greatest_common_divsor
result[1] = denominator / greatest_common_divsor
end
def gcd(a, b)
while b > 0
temp = b
b = a % b
a = temp
end
a
end
# slow version
def simplify_fraction(numerator, denominator, result)
result[0] = numerator
result[1] = denominator
gcd_upper_boound = [numerator, denominator].min
i = gcd_upper_boound
while i >= 2
if numerator % i == 0 && denominator % i == 0
result[0] = numerator / i
result[1] = denominator / i
break
end
i -= 1
end
end
result = Array.new(2)
simplify_fraction(77, 22, result) |
require_relative '../../spec_helper'
describe 'resurrector', type: :integration, hm: true do
with_reset_sandbox_before_each
before do
create_and_upload_test_release
upload_stemcell
end
let(:cloud_config_hash) do
cloud_config_hash = Bosh::Spec::NewDeployments.simple_cloud_config
cloud_config_hash['networks'].first['subnets'].first['static'] = ['192.168.1.10', '192.168.1.11']
cloud_config_hash
end
let(:simple_manifest) do
manifest_hash = Bosh::Spec::NewDeployments.simple_manifest_with_instance_groups
manifest_hash['instance_groups'].first['instances'] = 1
manifest_hash
end
it 'resurrects vms based on resurrection config' do
resurrection_config_enabled = yaml_file('config.yml', Bosh::Spec::NewDeployments.resurrection_config_enabled)
resurrection_config_disabled = yaml_file('config.yml', Bosh::Spec::NewDeployments.resurrection_config_disabled)
bosh_runner.run("update-config --type resurrection --name enabled #{resurrection_config_enabled.path}")
bosh_runner.run("update-config --type resurrection --name disabled #{resurrection_config_disabled.path}")
current_sandbox.reconfigure_health_monitor
deployment_hash = Bosh::Spec::NewDeployments.simple_manifest_with_instance_groups
deployment_hash['instance_groups'][0]['instances'] = 1
deployment_hash_enabled = deployment_hash.merge('name' => 'simple_enabled')
deployment_hash_disabled = deployment_hash.merge('name' => 'simple_disabled')
job_opts = {
name: 'foobar_without_packages',
jobs: [{ 'name' => 'foobar_without_packages', 'release' => 'bosh-release' }],
instances: 1,
}
deployment_hash_disabled['instance_groups'][1] = Bosh::Spec::NewDeployments.simple_instance_group(job_opts)
bosh_runner.run("upload-release #{spec_asset('dummy2-release.tgz')}")
upload_cloud_config(cloud_config_hash: Bosh::Spec::NewDeployments.simple_cloud_config)
# deploy simple_enabled
deploy_simple_manifest(manifest_hash: deployment_hash_enabled)
orig_instance_enabled = director.instance('foobar', '0', deployment_name: 'simple_enabled')
resurrected_instance = director.kill_vm_and_wait_for_resurrection(orig_instance_enabled, deployment_name: 'simple_enabled')
expect(resurrected_instance.vm_cid).to_not eq(orig_instance_enabled.vm_cid)
# deploy simple_disabled
deploy_simple_manifest(manifest_hash: deployment_hash_disabled)
instances = director.instances(deployment_name: 'simple_disabled')
orig_instance_enabled = director.find_instance(instances, 'foobar_without_packages', '0')
disabled_instance = director.find_instance(instances, 'foobar', '0')
resurrected_instance = director.kill_vm_and_wait_for_resurrection(orig_instance_enabled, deployment_name: 'simple_disabled')
expect(resurrected_instance.vm_cid).to_not eq(orig_instance_enabled.vm_cid)
disabled_instance.kill_agent
expect(director.wait_for_vm('foobar', '0', 150, deployment_name: 'simple_disabled')).to be_nil
end
end
|
module Platforms
module Yammer
module Api
# Networks on Yammer
# @author Benjamin Elias
# @since 0.1.0
class Networks < Base
# Get the user's current Network
# @param options [Hash] Options for the request
# @param headers [Hash] Additional headers to send with the request
# @return [Faraday::Response] the API response
# @see https://developer.yammer.com/docs/networkscurrentjson
def current options={}, headers={}
@connection.get 'networks/current.json', options, headers
end
end
end
end
end
|
class Api::V1::SmDirectoryController < Api::ApiController
require 'json'
respond_to :json
# == POST SOCIAL MEDIA DIRECTORY for a new movie by TMDB_ID
# === POST /api/v1/sm_directory/
# movietech.herokuapp.com/api/v1/sm_directory/<tmdb_id>
# adds social media directory for movie referenced by tmdb id where the the sm_directory table
# is not found.
# === Parameters
# tmdb_id: Integer(required). Example: 293660
# posts the movie titled Deadpool(2016)
# Request URL:http://localhost:9000/api/v1/sm_directory/
# === Headers
# Cache-Control:max-age=0, private, must-revalidate
# Connection:Keep-Alive
# Content-Type:application/json
# Authorization: Token token=5sdZCBgJyfWBZwhnijxgQwtt
# JSON body post
# Sample body json payload:
# {
# "tmdb_id": 293660,
# "title": "Deadpool",
# "fb_page_name": "fbname99999",
# "fb_id": "fbid 9999",
# "twitter_id": "twitter id 999999",
# "instagram_handle": "inst handle 99999",
# "instagram_id": "instagram id 999999",
# "klout_id": "klout id 999999",
# "release_date": "2016-09-09T00:00:00.000Z",
# "twitter_handle": "twitter handle 999999"
# }
def create #:nodoc:
req_parm = {}
no_response = {}
no_response['Error'] = 'Request failed.'
req_parm = JSON.parse(params[:sm_directory].to_json)
@sm_directory = SmDirectory.where(tmdb_id: params[:sm_directory][:tmdb_id]).first_or_create(req_parm)
DirectoryProcessor.new(@sm_directory).assign_social_media_ids
if @sm_directory && @sm_directory.save
respond_with(:api, :v1, @sm_directory)
else
respond_with :api, :v1, no_response, status: 404
end
end
# == PUT SOCIAL MEDIA DIRECTORY for an a TMDB id
# === PUT /api/v1/sm_directory/:tmdb_id
# updates social media directory for movie referenced by tmdb id
# Movie tmdb_id not modified.
# === Parameters
# tmdb_id: Integer(required). Example: 293660
# update the meta for the movie titled Deadpool(2016)
# Request URL: http://movietech.herokuapp.com/api/v1/sm_directory/293660
# === Headers
# Cache-Control:max-age=0, private, must-revalidate
# Connection:Keep-Alive
# Content-Type:application/json
# Authorization: Token token=5sdZCBgJyfWBZwhnijxgQwtt
# JSON body
# === Response
# JSON object: tmdb movie social media record
def update #:nodoc:
req_parm = {}
no_response = {}
no_response['Error'] = 'Request failed.'
req_parm = JSON.parse(params[:sm_directory].to_json)
@sm_directory = SmDirectory.where(tmdb_id: params[:sm_directory][:tmdb_id]).first
req_parm.except!('tmdb_id')
DirectoryProcessor.new(@sm_directory).assign_social_media_ids
if @sm_directory && @sm_directory.update(req_parm)
render json: @sm_directory
else
# respond_with :api, :v1, no_response, status: 404
render json: no_response, status: 404
end
end
# == GET SOCIAL MEDIA DIRECTORY for movie BY TMDB id
# === GET /api/v1/sm_directory/:tmdb_id
# gets social media directory referenced by tmdb id
# === Parameters
# tmdb_id: Integer(required). Example: 259694
# update the meta for the movie titled How To Be Single
# Request URL: http://movietech.herokuapp.com/api/v1/sm_directory/259694
# === Headers
# Cache-Control:max-age=0, private, must-revalidate
# Connection:Keep-Alive
# Content-Type:application/json
# Authorization: Token token=5sdZCBgJyfWBZwhnijxgQwtt
# JSON body
# === Response
# JSON object: tmdb movie social media record
def show
req_parm = {}
no_response = {}
req_parm[:tmdb_id] = params[:id]
@sm_directory = SmDirectory.where(req_parm).first
if @sm_directory
respond_with(directory: @sm_directory)
else
respond_with no_response, status: 404
end
end
private
end
|
require 'rails_helper'
RSpec.feature "Resources", type: :feature do
let(:user) { create(:user_with_path) }
let(:subject) { create(:subject) }
scenario "shows a resource with Markdown content" do
resource = create(:markdown, :published, subject: subject, content: "Hello World")
login(user)
visit subject_path(subject)
click_link resource.title
expect(current_path).to eq subject_resource_path(subject, resource)
expect(page).to have_content("Hello World")
end
scenario "displays Make it Real's icon when resource is own" do
resource = create(:resource, own: true, category: Resource.categories[:video_tutorial])
login(user)
visit subject_path(resource.subject)
within("tr#resource-#{resource.id}") do
expect(page).to have_selector(".label-mir")
expect(page).to have_selector(".resource-tag.#{resource.category}")
end
end
end
|
class ExportsController < ApplicationController
authorize_resource class: false
def index
end
def resx
if params[:culture]
language = Language.find_by_culture_string(params[:culture])
send_data render_resx(language), filename: resx_file_name(language, false)
else
files = Hash[Language.where('culture_string is not null').map{ |l| [resx_file_name(l, true), render_resx(l)] }]
send_data ZipArchive.create(files), filename: 'Strings.zip'
end
end
private
def render_resx(language)
#Doing raw SQL here is about 5 times faster than letting ActiveRecord do it
sql = <<-SQL
select
t.text,
r.name,
r.comment
from translations t
join resources r on t.resource_id = r.id
where t.language_id =
SQL
@translations = Translation.connection.select_all(sql + language.id.to_s)
render_to_string
end
def resx_file_name(language, is_zip)
if is_zip && language.name == 'English'
'Strings.resx'
else
"Strings.#{language.culture_string}.resx"
end
end
end
|
class AddPostToPostComments < ActiveRecord::Migration
def change
add_reference :post_comments, :post, index: true
end
end
|
class Season < ActiveRecord::Base
attr_accessible :name, :year
has_many :products
def name_year
"#{name} #{year.year}"
end
end
|
require 'spec_helper'
describe Bugsnag::Delivery::Fluent do
it 'has a version number' do
expect(Bugsnag::Delivery::Fluent::VERSION).not_to be nil
end
it 'registered to Bugsnag::Delivery' do
expect(Bugsnag::Delivery[:fluent]).to eq(described_class)
end
describe '.deliver' do
let(:fluent_logger) { double('Fluent::Logger::FluentLogger') }
let(:url) { 'http://www.example.com/' }
let(:body) { 'json body' }
let(:configuration) { Bugsnag.configuration }
let(:post_result) { nil }
subject { described_class.deliver(url, body, configuration, { headers: { 'Bugsnag-Payload-Version' => '4.0' } }) }
context 'send successful' do
before do
expect(::Fluent::Logger::FluentLogger).to receive(:new).and_return(fluent_logger)
data = { :url => url, :body => body, :options => { headers: { 'Bugsnag-Payload-Version' => '4.0' } } }
expect(fluent_logger).to receive(:post).with('deliver', data).and_return(true)
end
it do
expect(fluent_logger).to receive(:close)
expect(fluent_logger).to_not receive(:last_error)
expect(configuration).to_not receive(:warn)
subject
end
end
context 'send failed' do
context 'fluent logger return false' do
before do
expect(::Fluent::Logger::FluentLogger).to receive(:new).and_return(fluent_logger)
data = { :url => url, :body => body, :options => { headers: { 'Bugsnag-Payload-Version' => '4.0' } } }
expect(fluent_logger).to receive(:post).with('deliver', data).and_return(false)
end
it do
expect(fluent_logger).to receive(:close)
expect(fluent_logger).to receive(:last_error).and_return('LAST ERROR')
expect(configuration).to receive(:warn).with('Notification to http://www.example.com/ failed, LAST ERROR')
subject
end
end
context 'fluent logger raise exception' do
before do
expect(::Fluent::Logger::FluentLogger).to receive(:new).and_return(fluent_logger)
data = { :url => url, :body => body, :options => { headers: { 'Bugsnag-Payload-Version' => '4.0' } } }
expect(fluent_logger).to receive(:post).with('deliver', data).and_raise
end
it do
expect(fluent_logger).to receive(:close)
expect(fluent_logger).to_not receive(:last_error)
expect(configuration).to receive(:warn).exactly(2).times
subject
end
end
end
context 'connection failure' do
it 'return' do
exception = StandardError.new('Connection Failure')
expect(Fluent::Logger::FluentLogger).to receive(:new).and_raise(exception)
expect(configuration).to receive(:warn).exactly(2).times
subject
end
end
end
end
|
class Message < ApplicationRecord
belongs_to :photos, optional: true
with_options presence: true do
validates :name
validates :text
end
end
|
module Moonrope
class InstallGenerator < Rails::Generators::Base
desc "This generator creates your a Moonrope directory structure"
def generate_directories
empty_directory 'api/controllers'
empty_directory 'api/helpers'
empty_directory 'api/structures'
end
end
end
|
require File.expand_path(File.dirname(__FILE__) + '/spec_helper')
describe RapperLite do
Dir["spec/fixtures/testcases/*/"].each do |folder|
name = File.basename( folder )
paths = [
{
:results => "tmp/*.js",
:expecteds => "#{folder}expected/*.js",
},
{
:results => "tmp/*.css",
:expecteds => "#{folder}expected/*.css",
}
]
it "passes the \"#{name}\" test case" do
rapper = RapperLite::Engine.new( "#{folder}/rapper.yml" )
rapper.package
paths.each do |path|
# Produces the same exact individual files
file_names( path[:results] ).should == file_names( path[:expecteds] )
# Contents are all the same
results = Dir[ path[:results] ]
expecteds = Dir[ path[:expecteds] ]
results.each_index do |i|
unless File.read( results[i] ) == File.read( expecteds[i] )
puts
puts File.read( results[i] )
puts
raise "#{results[i]} did not match #{expecteds[i]}"
end
end
end
end
end
end
|
class ProjectMediaProject < ActiveRecord::Base
attr_accessor :previous_project_id, :set_tasks_responses
include CheckElasticSearch
include CheckPusher
include ValidationsHelper
has_paper_trail on: [:create, :update], if: proc { |_x| User.current.present? }, class_name: 'Version'
belongs_to :project
belongs_to :project_media
validates_presence_of :project, :project_media
validate :project_is_not_archived, unless: proc { |pmp| pmp.is_being_copied }
after_commit :update_index_in_elasticsearch, :add_remove_team_tasks, on: [:create, :update]
after_destroy :update_index_in_elasticsearch
after_commit :remove_related_team_tasks, on: :destroy
after_save :send_pmp_slack_notification
notifies_pusher on: [:save, :destroy],
event: 'media_updated',
targets: proc { |pmp| [pmp.project, pmp.project&.team, pmp.project_was] },
data: proc { |pmp| { id: pmp.id }.to_json }
def check_search_team
team = self.team
team.check_search_team
end
def check_search_trash
team = self.team
team.check_search_trash
end
def check_search_project(project = nil)
project ||= self.project
return nil if project.nil?
project.check_search_project
end
def check_search_project_was
self.check_search_project(self.project_was)
end
def project_was
Project.find_by_id(self.previous_project_id) unless self.previous_project_id.blank?
end
def graphql_deleted_id
self.project_media.graphql_id
end
def team
@team || self.project&.team
end
def team=(team)
@team = team
end
def is_being_copied
self.team && self.team.is_being_copied
end
def self.bulk_create(inputs, team)
# Filter IDs
pmids = ProjectMedia.where(id: inputs.collect{ |input| input['project_media_id'] }, team_id: team.id).select(:id).map(&:id)
pids = Project.where(id: inputs.collect{ |input| input['project_id'] }, team_id: team.id, archived: false).select(:id).map(&:id)
inserts = []
inputs.each do |input|
inserts << input.to_h if pmids.include?(input['project_media_id']) && pids.include?(input['project_id'])
end
# Bulk-insert in a single SQL
result = ProjectMediaProject.import inserts, validate: false, recursive: false, timestamps: true, on_duplicate_key_ignore: true
# Bulk-update medias count of each project
Project.bulk_update_medias_count(pids)
# Other callbacks to run in background
ProjectMediaProject.delay.run_bulk_save_callbacks(result.ids.map(&:to_i).to_json, User.current&.id)
# Notify Pusher
team.notify_pusher_channel
# Return first (hopefully only, for the Check Web usecase) project and notify
first_project = Project.find_by_id(pids[0])
first_project&.notify_pusher_channel
{ team: team, project: first_project }
end
def self.run_bulk_save_callbacks(ids_json, user_id)
current_user = User.current
User.current = User.find_by_id(user_id.to_i)
ids = JSON.parse(ids_json)
ids.each do |id|
pmp = ProjectMediaProject.find(id)
[:send_pmp_slack_notification, :update_index_in_elasticsearch, :add_remove_team_tasks].each { |callback| pmp.send(callback) }
end
User.current = current_user
end
def self.filter_ids_by_team(input_ids, team)
pids = []
pmids = []
ids = []
pairs = []
ProjectMediaProject
.joins(:project, :project_media)
.where(id: input_ids, 'projects.team_id' => team.id, 'project_medias.team_id' => team.id)
.select('project_media_projects.id AS id, projects.id AS pid, project_medias.id AS pmid')
.each do |pmp|
ids << pmp.id
pids << pmp.pid
pmids << pmp.pmid
pairs << { project_id: pmp.pid, project_media_id: pmp.pmid }
end
[ids.uniq, pids.uniq, pmids.uniq, pairs]
end
def self.bulk_destroy(input_ids, fields, team)
# Filter IDs that belong to this team in a single SQL
ids, pids, pmids, pairs = self.filter_ids_by_team(input_ids, team)
pm_graphql_ids = pmids.collect{ |pmid| Base64.encode64("ProjectMedia/#{pmid}") }
# Bulk-delete in a single SQL
ProjectMediaProject.where(id: ids).delete_all
# Bulk-update medias count of each project
Project.bulk_update_medias_count(pids)
# Other callbacks to run in background
ProjectMediaProject.delay.run_bulk_destroy_callbacks(pmids.to_json, pairs.to_json)
project_was = Project.where(id: fields[:previous_project_id], team_id: team.id).last unless fields[:previous_project_id].blank?
# Notify Pusher
team.notify_pusher_channel
project_was&.notify_pusher_channel
{ team: team, project_was: project_was, check_search_project_was: project_was&.check_search_project, ids: pm_graphql_ids }
end
def self.run_bulk_destroy_callbacks(pmids_json, pairs_json)
ids = JSON.parse(pmids_json)
pairs = JSON.parse(pairs_json)
ids.each do |id|
pm = ProjectMedia.find(id)
pm.update_elasticsearch_doc(['project_id'], { 'project_id' => { method: 'project_ids', klass: 'ProjectMedia', id: pm.id } }, pm)
end
pairs.each { |pair| self.remove_related_team_tasks_bg(pair['project_id'], pair['project_media_id']) }
end
def self.bulk_update(input_ids, updates, team)
# For now let's limit to project_id updates
return {} if updates.keys.map(&:to_s) != ['project_id'] &&
updates.keys.map(&:to_s).sort != ['previous_project_id', 'project_id']
project = Project.where(id: updates[:project_id], team_id: team.id).last
return {} if project.nil?
# Filter IDs that belong to this team in a single SQL
ids, pids, pmids, _pairs = self.filter_ids_by_team(input_ids, team)
pm_graphql_ids = pmids.collect{ |pmid| Base64.encode64("ProjectMedia/#{pmid}") }
# Bulk-update in a single SQL
ProjectMediaProject.where(id: ids).update_all(project_id: updates[:project_id])
# Bulk-update medias count of each project
Project.bulk_update_medias_count(pids.concat([updates[:project_id]]))
# Other callbacks to run in background
ProjectMediaProject.delay.run_bulk_save_callbacks(ids.to_json, User.current&.id)
project_was = Project.where(id: updates[:previous_project_id], team_id: team.id).last unless updates[:previous_project_id].blank?
# Notify Pusher
team.notify_pusher_channel
project.notify_pusher_channel
project_was&.notify_pusher_channel
{ team: team, project: project, project_was: project_was, check_search_project_was: project_was&.check_search_project, ids: pm_graphql_ids }
end
def slack_channel(event)
slack_events = self.project.setting(:slack_events)
slack_events ||= []
slack_events.map!(&:with_indifferent_access)
selected_event = slack_events.select{|i| i['event'] == event }.last
selected_event.blank? ? nil : selected_event['slack_channel']
end
def slack_notification_message
self.project_media.slack_notification_message
end
private
def project_is_not_archived
parent_is_not_archived(self.project, I18n.t(:error_project_archived)) unless self.project.nil?
end
def add_remove_team_tasks
only_selected = ProjectMediaProject.where(project_media_id: self.project_media_id).count > 1
project_media = self.project_media
project_media.set_tasks_responses = self.set_tasks_responses
project_media.add_destination_team_tasks(self.project, only_selected)
end
def remove_related_team_tasks
TeamTaskWorker.perform_in(1.second, 'remove_from', self.project_id, YAML::dump(User.current), YAML::dump({ project_media_id: self.project_media_id }))
end
def self.remove_related_team_tasks_bg(pid, pmid)
# Get team tasks that assigned to target list (pid)
tasks = TeamTask.where("project_ids like ?", "% #{pid}\n%")
# Get tasks with zero answer (should keep completed tasks)
Task.where('annotations.annotation_type' => 'task', 'annotations.annotated_type' => 'ProjectMedia', 'annotations.annotated_id' => pmid)
.where('task_team_task_id(annotations.annotation_type, annotations.data) IN (?)', tasks.map(&:id))
.joins("LEFT JOIN annotations responses ON responses.annotation_type LIKE 'task_response%'
AND responses.annotated_type = 'Task'
AND responses.annotated_id = annotations.id"
)
.where('responses.id' => nil).find_each do |t|
t.skip_check_ability = true
t.destroy
end
end
def update_index_in_elasticsearch
return if self.disable_es_callbacks
self.update_elasticsearch_doc(['project_id'], { 'project_id' => { method: 'project_ids', klass: 'ProjectMedia', id: self.project_media_id } }, self.project_media)
end
def send_pmp_slack_notification
self.send_slack_notification('item_added')
end
end
|
# encoding: utf-8
module Faceter
module Functions
# Break the array to array of consecutive items that matches each other
# by given function
#
# @param [Array] list
# @param [#call] fn
#
# @return [Array]
#
def self.claster(list, fn)
list.each_with_object([[]]) do |e, a|
if a.last.eql?([]) || fn[e].equal?(fn[a.last.last])
a.last << e
else
a << [e]
end
end
end
end # module Functions
end # module Faceter
|
require 'rails_helper'
describe "user visits destinations edit page" do
context "as an admin" do
it "allows admin to edit destinations" do
admin = create(:user, role: 1)
destination = create(:destination)
allow_any_instance_of(ApplicationController).to receive(:current_user).and_return(admin)
visit edit_admin_destination_path(destination)
expect(page).to have_content("Admin - Edit #{destination.city}, #{destination.state}")
fill_in "destination[city]", with: "Pawnee"
fill_in "destination[state]", with: "IN"
fill_in "destination[latitude]", with: 35.0000001
fill_in "destination[longitude]", with: 65.0000001
fill_in "destination[population]", with: 114123
click_on "Update Destination"
last_destination = Destination.last
expect(current_path).to eq(destination_path(last_destination))
end
end
context "as a default user" do
it "does not allow default user to see admin edit destinations page" do
user = create(:user)
destination = create(:destination)
allow_any_instance_of(ApplicationController).to receive(:current_user).and_return(user)
visit edit_admin_destination_path(destination)
expect(page).to_not have_content("Admin - Create Destination")
expect(page).to have_content("The page you were looking for doesn't exist")
end
end
end
|
require 'rubygems'
require 'spec'
require 'backseat'
include Backseat::Helpers
describe 'a simple test' do
before(:all) do
Backseat.load!
@driver = Backseat::Driver.new(:firefox)
end
it "should do some basic navigation" do
@driver.get('http://localhost:3000/products')
@driver.should have_at_least(2).elements(div(:class => 'album_product'))
@driver[h2.a].click
@driver.should have(1).elements(ol(:class => 'track_list'))
@driver[ol(:class => 'track_list')].should have(4).elements(li)
end
after(:all) do
@driver.close
end
end
|
require 'rails_helper'
describe PeerEval, type: :model do
describe 'associations' do
it { should belong_to(:user) }
it { should belong_to(:creator).class_name("User") }
it { should belong_to(:milestone) }
end
describe 'validations' do
it { should validate_presence_of(:milestone) }
it { should validate_presence_of(:goals) }
it { should validate_presence_of(:quality) }
it { should validate_presence_of(:effort) }
it { should validate_presence_of(:considerate) }
it { should validate_presence_of(:knowledge) }
it { should validate_presence_of(:sharing) }
it { should validate_presence_of(:strength) }
it { should validate_presence_of(:weakness) }
end
end |
class AddOriginalAmountToBlockchainTransactions < ActiveRecord::Migration
def down
remove_column :spree_blockchain_transactions, :order_total
end
def up
add_column :spree_blockchain_transactions, :order_total, :decimal
end
end
|
class TradeGood < ActiveRecord::Base
# serialize :available
# serialize :purchase_dm
# serialize :sale_dm
has_many :broker_trade_goods
has_many :trade_code_goods
has_many :available_trade_code_goods, -> {where(kind: 'available')}, class_name: "TradeCodeGood"
has_many :available_trade_codes, through: :available_trade_code_goods, class_name: "TradeCode", source: :trade_code
has_many :purchase_trade_code_goods, -> {where(kind: 'purchase')}, class_name: "TradeCodeGood"
has_many :purchase_trade_codes, through: :purchase_trade_code_goods, class_name: "TradeCode", source: :trade_code
has_many :sale_trade_code_goods, -> {where(kind: 'sale')}, class_name: "TradeCodeGood"
has_many :sale_trade_codes, through: :sale_trade_code_goods, class_name: "TradeCode", source: :trade_code
scope :available_in, -> (system) {
joins(:available_trade_codes)
.where(trade_codes: {id: system.trade_code_ids})
.uniq
}
# def self.items_for(system)
# items = for_code("All")
# system.trade_codes.each do |code|
# items += for_code(code)
# end
# items.uniq
# end
def self.special_items(n)
items = []
n.times do
res = (rand(6)+1)*10 +rand(6)+1
items << find_by_d66(res)
end
items
end
# def self.for_code(code)
# where("available LIKE '%- #{code}%'")
# end
def purchase_price_mod(system)
mod_for(:purchase, system) - mod_for(:sale, system)
end
def sale_price_mod(system)
mod_for(:sale, system) - mod_for(:purchase, system)
end
# def mod_for(kind, system)
# mod = 0
# send(attr).each do |code|
# name, mod_for_code = code.split(/((\+|\-)\d+)/)
# name = name.strip
# mod_for_code = mod_for_code.to_i
# if system.trade_codes.include?(name)
# mod = [mod, mod_for_code].max
# end
# if name == 'Amber Zone' && system.travel_code == 'Amber'
# mod = [mod_for_code, mod].max
# end
# if name == 'Red Zone' && system.travel_code == 'Red'
# mod = [mod_for_code, mod].max
# end
# end
# end
def mod_for(kind, system)
mod = 0
send(:"#{kind}_trade_code_goods").where(trade_code_goods:
{trade_code_id: system.trade_code_ids}
).each do |item|
mod = [item.dm, mod].max
end
mod
end
end
|
class Ships
attr_reader :validated_coordinates, :game_board
def initialize(validated_coordinates, game_board = GameBoard.new)
@validated_coordinates = validated_coordinates
@game_board = game_board
end
def mark_ships
@validated_coordinates.each do |coordinate|
ship_placement = @game_board.find_game_square(coordinate)
ship_placement[coordinate] = true
end
store_ship_placements
end
def store_ship_placements
if @validated_coordinates.length == 3
@game_board.three_unit_ship << @validated_coordinates
else
@game_board.two_unit_ship << @validated_coordinates
end
end
end
|
class RemoveFriend < ActiveRecord::Migration
def up
drop_table :friends
end
def down
create_table :friends do |t|
t.integer :user_id
t.string :name
t.boolean :declared
t.date :last_accompanied
t.integer :accompaniment_frequency
t.timestamps
end
end
end
|
require 'test_helper'
class TitlematchesControllerTest < ActionController::TestCase
setup do
@titlematch = titlematches(:one)
end
test "should get index" do
get :index
assert_response :success
assert_not_nil assigns(:titlematches)
end
test "should get new" do
get :new
assert_response :success
end
test "should create titlematch" do
assert_difference('Titlematch.count') do
post :create, titlematch: { date_won: @titlematch.date_won, title_id: @titlematch.title_id, user: @titlematch.user }
end
assert_redirected_to titlematch_path(assigns(:titlematch))
end
test "should show titlematch" do
get :show, id: @titlematch
assert_response :success
end
test "should get edit" do
get :edit, id: @titlematch
assert_response :success
end
test "should update titlematch" do
put :update, id: @titlematch, titlematch: { date_won: @titlematch.date_won, title_id: @titlematch.title_id, user: @titlematch.user }
assert_redirected_to titlematch_path(assigns(:titlematch))
end
test "should destroy titlematch" do
assert_difference('Titlematch.count', -1) do
delete :destroy, id: @titlematch
end
assert_redirected_to titlematches_path
end
end
|
module ApplicationHelper
def nav_categories (cat)
cat.map do |c|
if c.articles.count > 0
content_tag :li do
link_to c.name, category_path(c.permalink)
end
end
end.reject{ |e| e.nil? }.reduce(&:+)
end
def page_title site_name, title
if action_name == 'home'
content_tag :title, site_name
else
content_tag :title, "#{title} | #{site_name}"
end
end
def meta_desc_tag(desc)
tag(:meta, name: 'description', content: desc) unless desc.nil?
end
def og_tag(hsh)
hsh.map {|key, value| tag(:meta, property: "og:#{key}" , content: value)}.inject(&:+) if hsh.present?
end
def tracking_tags gtm, ga
{'gtm': gtm,'ga': ga}.map do |key, value|
render "tracking/#{key}" if value.present?
end.join.html_safe
end
end |
module EasyPatch
module DateHelperPatch
def self.included(base)
base.send(:include, InstanceMethods)
base.class_eval do
def time_ago_in_words_ex(from_time, label_not_expired = "", label_expired = "", include_seconds = false)
result = time_ago_in_words(from_time + 1.day, include_seconds)
(Time.now - (from_time.to_time + 1.day)) > 0 ? "<span>#{label_expired}</span><span class=""overdue"">#{result}</span>".html_safe : "<span class=""date-not-overdue"">#{label_not_expired}</span><span>#{result}</span>".html_safe
end
end
end
module InstanceMethods
end
end
end
EasyExtensions::PatchManager.register_rails_patch 'ActionView::Helpers::DateHelper', 'EasyPatch::DateHelperPatch'
|
def get_name
puts "I'm great at conversions. What's your name?"
gets.chomp
end
def get_feet welcome_name
puts "Welcome #{welcome_name}!!! How many feet tall are you?"
height_feet = gets.chomp.to_i
if height_feet.zero?
puts "Zero feet tall? Try again:"
height_feet = get_feet welcome_name
elsif height_feet > 9
puts "WOW! How's the weather up there? Let's try again!"
height_feet = get_feet("Skyscraper!")
end
height_feet
end
def get_inches
puts "And how many inches?"
height_inches = gets.chomp.to_i
if height_inches >11
puts "This should be between 0 and 11, so try again."
height_inches = get_inches
end
height_inches
end
def get_weight
puts "And what do you weigh?"
weight_pounds = gets.chomp.to_i
if weight_pounds.zero?
puts "I really doubt that. Try again:"
weight_pounds = get_weight
elsif weight_pounds < 45
puts "Eat a hamburger!"
end
weight_pounds
end
my_name = get_name
height_feet = get_feet(my_name)
height_inches = get_inches
weight_pounds = get_weight
total_height_inches = (12 * height_feet) + height_inches
height_centimeters = total_height_inches * 2.54
weight_kilograms = weight_pounds * 0.453592
puts "\n#{my_name} is #{height_centimeters}cm and #{weight_kilograms}kg" |
require 'optparse'
require "#{File.dirname(__FILE__)}/auth.rb"
require File.expand_path(File.dirname(__FILE__) + '/../googlepub')
module Googlepub
class Options
BANNER = <<-EOS
Googlepub it gem for Google Android Publisheing API.
Abilities:
1) Store Listing
2) APK - All tracks
3) In-App Purchases (Managed and Subscriptions)
Usage:
googlepub COMMAND [OPTIONS]
Main commands:
apk. metadata, inapps
Example:
googlepub metadata -l "en-US" -p "com.keshav.goel" --store -t "Title" -s "Short Description" -f "fullDescription" --icon "icon.png"
googlepub apk -p "com.keshav.goel" --file "file.apk" --track "beta"
googlepub inapps -p "com.keshav.goel" --sku "com.keshav.inapp.12" --title "InApp 12" --fullDescription "Description" --price 1990000
Dependencies:
Ruby, HTTP
Author: @thekeshavgoel
Email: keshu_gl@yahoo.com
EOS
# Creating a CommandLine runs off of the contents of ARGV.
def initialize
parse_options
cmd = ARGV.shift
@command = cmd && cmd.to_sym
@auth = Googlepub::Auth.new(@options)
if @command != :inapps
@auth.edit
run
@auth.validate_edit
@auth.commit_edit
else
run
end
end
def run
begin
case @command
when :apk then puts Googlepub.call_apk(@options)
when :metadata then puts Googlepub.call_metadata(@options)
when :inapps then puts Googlepub.call_inapps(@options)
else
puts "Please provide command to Excute - 'apk' or 'metadata'"
exit (1)
end
end
end
# Print out the usage help message.
def usage
puts "\n#{@option_parser}\n"
exit
end
private
def parse_options
@options = {"language" => "en-US", "currency" => "USD"}
@option_parser = OptionParser.new do |opts|
opts.on('-l', '--language [LANGUAGE]', 'The ISO language code (default: "en-US")') do |l|
@options["language"] = l
end
opts.on('-k', '--key [KEY]', "Key for the Account from Google Developer Console (ENV['KEY'])") do |l|
@options["key"] = l
end
opts.on('-i', '--iss [ISSUER]', "ISS for the Account from Google Developer Console (ENV['ISS'])") do |l|
@options["iss"] = l
end
opts.on('-p', '--package [PACKAGE]', "Package to update on the Google Developer Console (ENV['PACKAGE'])") do |pa|
@options["package"] = pa
end
opts.on('--store', 'Specify that Store Listing details are to be Updated.') do |s|
@options["store"] = s
end
opts.on('-t', '--title [TITLE]', 'Name for your App/In-App') do |k|
@options["title"] = k
end
opts.on('-f', '--full [FULLDESCRIPTION]', 'Full Description for your App/Description for your In-App') do |t|
@options["fullDescription"] = t
end
opts.on('-s', '--short [SHORTDESCRIPTION]', 'Short Description for your App') do |d|
@options["shortDescription"] = d
end
opts.on('-v', '--video [VIDEO]', 'Youtube Video URL') do |o|
@options["video"] = o
end
opts.on('--details', 'Specify that the details are to be updated (Website, Email and Phone)') do |c|
@options["details"] = true
end
opts.on('-w', '--website [WEBSITE]', 'Website for Contact') do |l|
@options["website"] = l
end
opts.on('-e', '--email [EMAIL]', 'Email for Contact') do |n|
@options["email"] = n
end
opts.on('--phone [PHONE]', 'Phone for Contact') do |r|
@options["phone"] = r
end
opts.on('--screenshots', 'Specify that Screenshots are to be updated for Contact') do |r|
@options["screenshots"] = r
end
opts.on('--featureGraphic [PATH]', 'featureGraphic for your App eg: "path/to/file"') do |r|
@options["featureGraphic"] = r
end
opts.on('--icon [PATH]', 'icon for your App eg: "path/to/file"') do |z|
@options["icon"] = z
end
opts.on('--phoneScreenshots [PATH]', 'phoneScreenshots for your App (comma separated) eg: "path/to/file1,path/to/file1,.."') do |r|
@options["phoneScreenshots"] = r
end
opts.on('--promoGraphic [PATH]', 'promoGraphic for your App eg: "path/to/file"') do |r|
@options["promoGraphic"] = r
end
opts.on('--sevenInch [PATH]', 'sevenInchScreenshots for your App (comma separated) eg: "path/to/file1,path/to/file1,.."') do |r|
@options["sevenInchScreenshots"] = r
end
opts.on('--tenInch [PATH]', 'tenInchScreenshots for your App (comma separated) eg: "path/to/file1,path/to/file1,.."') do |r|
@options["tenInchScreenshots"] = r
end
opts.on('--tvBanner [PATH]', 'tvBanner for your App (comma separated) eg: "path/to/file1,path/to/file1,.."') do |r|
@options["tvBanner"] = r
end
opts.on('--tv [PATH]', 'tvScreenshots for your App (comma separated) eg: "path/to/file1,path/to/file1,.."') do |r|
@options["tvScreenshots"] = r
end
opts.on('--wear [PATH]', 'wearScreenshots for your App (comma separated) eg: "path/to/file1,path/to/file1,.."') do |r|
@options["wearScreenshots"] = r
end
opts.on('--file [PATHTOFILE]', 'APK file to upload eg: "path/to/file"') do |r|
@options["file"] = r
end
opts.on('--track [TRACK]', 'Track to which APK file is to be uploaded eg: "beta"') do |r|
@options["track"] = r
end
opts.on('--apkversion [Version]', 'Code Version of your APK you want to deploy') do |r|
@options["status"] = r.downcase
end
opts.on('--sku [SKU]', 'The SKU of the In-App you wish to edit') do |r|
@options["sku"] = r
end
opts.on('--price [PRICE]', 'Price for the In-App in Decimal(eg: 5.99), Will convert to Millionth by self') do |r|
@options["price"] = r
end
opts.on('--curr [CURR]', '3 letter Currency code, as defined by ISO 4217 for your SKU (USD by default)') do |r|
@options["currency"] = r.upcase
end
opts.on('--status [STATUS]', 'Status for your In-App, "active" or "inactive"') do |r|
@options["status"] = r.downcase
end
opts.on_tail('--version', 'Display googlepub version') do
puts "Googlepub version #{Googlepub::VERSION}"
exit
end
opts.on_tail('-h', '--help', 'Display this help message') do
usage
end
end
@option_parser.banner = BANNER
begin
@option_parser.parse!(ARGV)
rescue OptionParser::InvalidOption => e
puts e.message
exit(1)
end
end
end
end
|
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe StringLengthLastWord do
let(:error_message) { 'String cannot be less than 1 or greater than 104 characters' }
let(:challenge) { described_class.new(str).call }
describe '.call' do
context "when phrase ' fly me to the moon '" do
let(:str) { ' fly me to the moon ' }
it { expect(challenge).to eq(4) }
end
context "when phrase 'Hello World'" do
let(:str) { 'Hello World' }
it { expect(challenge).to eq(5) }
end
context "when phrase 'helloween is a great band'" do
let(:str) { 'helloween is a great band' }
it { expect(challenge).to eq(4) }
end
context "when phrase 'luffy is still joyboy'" do
let(:str) { 'luffy is still joyboy' }
it { expect(challenge).to eq(6) }
end
context 'when raise empty string' do
let(:str) { '' }
it { expect { challenge }.to raise_error(error_message) }
end
context 'when raise string greater than 104 characters' do
let(:str) do
'is simply dummy text of the printing and typesetting industry. '\
"Lorem Ipsum has been the industry's stanAa 12 "
end
it { expect { challenge }.to raise_error(error_message) }
end
end
end
|
class AnswersController < ApplicationController
before_action :signed_in_user, only: :show
def show
@answers = Answer.where("question_id = #{params[:id]}")
@correct = @answers.where("correct_answer = true").shuffle.first
@incorrect = @answers.where("correct_answer = false").shuffle.take(3)
@final = @correct + @incorrect
render json: @final.shuffle
end
end |
class UpdateGame
@queue = :update_game
def self.perform(game_id)
Game.find(game_id).refresh_status!
end
end
|
json.array!(@dinnings) do |dinning|
json.extract! dinning, :id, :quantity, :price, :rate, :user_id
json.url dinning_url(dinning, format: :json)
end
|
class CreateMedicines < ActiveRecord::Migration
def change
create_table :medicines do |t|
t.string :nombre
t.string :cantidad
t.text :indicaciones
t.string :laboratorio
t.string :composicion
t.text :posologia
t.text :detalle
t.string :efectos_colaterales
t.string :contraendicaciones
t.string :observaciones
t.timestamps null: false
end
end
end
|
class RenameColumnLeadInMovies < ActiveRecord::Migration
def change
rename_column :movies, :lead_actor_or_actress, :lead
end
end
|
class Country < ApplicationRecord
mount_uploader :country_image, CountryUploader
has_many :states
has_many :cities
has_many :companies
has_many :places
has_many :nodes
validates :country_name, presence: true,
length: { minimum: 3 }
validates :country_name, uniqueness: true
end
|
module Input
def get_name
print "What is your name? "
name = gets.chomp.downcase.split(" ").each {|word| word.capitalize!}.join(" ")
print %x{clear}
name
end
def get_guess
guess = gets.chomp.downcase
if guess == "save"
else
if guess.length > 1
puts "A valid guess must only be one letter"
guess = nil
elsif guess.scan(/\d/).empty? == false
puts "You are not allowed to guess numbers!"
guess = nil
end
end
guess
end
def get_answer
entry = nil
until entry != nil
print "\nWould you like to start a new game (new) or load a saved game (load)? "
entry = case gets.chomp.downcase
when "new", "n" then "new"
when "load", "l" then "load"
else nil
end
puts "That is not a valid option, new or load?" if entry.nil?
end
entry
end
def play_again?
entry = nil
until entry != nil
print "\nWould you like to play again? "
entry = case gets.chomp.downcase
when "yes", "y" then true
when "no", "n" then false
else nil
end
puts "That is not a valid option, yes or no" if entry.nil?
end
entry
end
end
module Game_functions
require "yaml"
def run(name)
play = true
until not play
game = Hangman.new(name)
function = game.play
if function == "save"
save(game)
play = false
else
play = play_again?
end
end
close
end
def save(game)
Dir.mkdir("saved_games") unless Dir.exists? "saved_games"
look = true
while look == true
print "\nPlease enter a unique identifier used to load your game again: "
id = gets.chomp.downcase
until id != "exit"
print "\nYou won't be able to load it with exit. Try a different id: "
id = gets.chomp.downcase
end
filename = "saved_games/saved_game_#{id}.txt"
if File.file?(filename) == false
File.open(filename, 'w') {|f| f.write(YAML.dump(game)) }
print "Saving Game."
sleep(1)
print "."
sleep(1)
print "."
sleep(1)
puts "Game has succesfully saved!"
puts
look = false
else
puts "There is already a game saved with that id, try a different one!"
end
end
end
def load
Dir.mkdir("saved_games") unless Dir.exists? "saved_games"
look = true
while look == true
print "\nWhat is the unique identifier you saved your game with? "
id = gets.chomp.downcase
if id == "exit"
game = "exit"
look = false
else
filename = "saved_games/saved_game_#{id}.txt"
if File.file?(filename)
game = YAML.load(File.read(filename))
print %x{clear}
print "Loading Game."
sleep(1)
print "."
sleep(1)
print "."
sleep(1)
look = false
File.delete(filename)
else
puts "There is no saved game with that id, please try again..."
end
end
end
game
end
def close
puts "Thanks for playing!"
sleep(3)
print %x{clear}
end
end |
class StaticPagesController < ApplicationController
# Displays Contact us
def contactus
@static_page = StaticPage.find_by_name("contactus")
render "contactus"
end
# Displays About us
def aboutus
@static_page = StaticPage.find_by_name("aboutus")
render "aboutus"
end
# Displays faq
def faq
render "faq"
end
# Creates an instance of Enquiry
def new_enquiry
@enquiry = Enquiry.new
render "new_enquiry"
end
# Creates Enquiry
def create_enquiry
@static_page = StaticPage.find_by_name("contactus")
@enquiry = Enquiry.new(params[:enquiry])
if @enquiry.save
flash[:notice] = "Your equiry has been send."
render "contactus"
else
flash[:notice] = "Error Occured."
render "contactus"
end
end
end |
require 'minitest/spec'
require 'minitest/autorun'
require File.expand_path(File.join('..', 'lib/parser.rb'), File.dirname(__FILE__))
require File.expand_path(File.join('..', 'lib/pbxproj_validator.rb'), File.dirname(__FILE__))
describe Pbxproj::PbxProject do
describe "printing" do
before do
content = <<'END_PBXPROJ_CONTENT'
// !$*UTF8*$!
{
objects = {
/* Begin PBXContainerItemProxy section */
8C00F4AD141D251100CCAB3D /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = 8C00F47C141D251000CCAB3D /* Project object */;
proxyType = 1;
remoteGlobalIDString = 8C00F484141D251000CCAB3D;
remoteInfo = "Valid Example Project";
};
/* End PBXContainerItemProxy section */
};
}
END_PBXPROJ_CONTENT
@project = Parser.parse(content)
@project.must_be_instance_of Pbxproj::PbxProject
end
it "can print the project" do
skip "PENDING"
@project.print.wont_be_nil
end
end
describe "validation" do
describe "inspecting app targets" do
describe "find redundant resources" do
it "identifies the redundant resources" do
skip "PENDING"
end
end
describe "find missing resources" do
it "identifies the missing resources" do
skip "PENDING"
end
end
end
describe "associating spec targets with the targets they test" do
describe "find missing resources" do
it "identifies missing specs" do
skip "PENDING"
end
it "identifies missing classes" do
skip "PENDING"
end
it "identifies missing resources" do
skip "PENDING"
end
end
describe "find redundant resources" do
it "identifies the redundant resources" do
skip "PENDING"
end
end
end
describe "associating test targets with the targets they test" do
describe "find missing resources" do
it "identifies the missing resources" do
skip "PENDING"
end
end
describe "find redundant resources" do
it "identifies the redundant resources" do
skip "PENDING"
end
end
end
describe "associating SenTestKit targets with the targets they test" do
describe "find redundant resources" do
it "identifies the redundant resources" do
skip "PENDING"
end
end
end
end
end |
# frozen_string_literal: true
require_relative '../../lib/utils/normalize_content'
# @param [Discordrb::Events::MessageEventHandler] event
def roll(event)
content = normalize_content event.content
puts content
event.channel.send_embed('') do |embed|
embed.title = 'You made a roll!!'
embed.description = 'Lets see them rolls bb!'
embed.colour = 0xff00c8
embed.add_field(name: 'Query:', value: format('%<author_id>s', opts))
embed.add_field(name: 'Rolls:', value: format('%<recipient>s', opts))
embed.add_field(name: 'Sum:', value: format('%<recipient>s', opts))
end
end |
require_relative '../rails_helper'
describe FrontendHomepageController do
describe "GET #show" do
it "assigns the correct homepage to @homepage" do
homepage = create(:homepage_published)
get :show
expect(assigns(:homepage)).to eq(homepage)
end
it "displays the homepage" do
homepage = create(:homepage_published)
get :show
expect(response).to render_template :show_homepage
end
end
end
|
class AddIconToCategory < ActiveRecord::Migration
def change
add_column :categories, :icon, :string, default: nil
end
end
|
class Tag < ActiveRecord::Base
has_many :posts, :through => :post_tags
has_many :post_tags
has_many :services, :through => :service_tags
has_many :service_tags
validates :name,
presence: true
end |
attributes *ComboItem.column_names - ['created_at', 'updated_at', 'name', 'menu_id']
if locals[:item].gmi?(locals[:menu_id])
#List of items in GMI
child :combo_item_categories => "GMI_items" do
attributes :sequence, :quantity
node(:categories) do |c|
partial('category/items', :object => c.category, locals: {category_id: c.id, menu_id: locals[:menu_id], user_id: locals[:user_id]})
end
end
#List of items in PMI
child :combo_item_items => "PMI_items" do
end
elsif locals[:item].pmi?(locals[:menu_id])
#List of items in GMI
child :combo_item_categories => "GMI_items" do
end
#List of items in PMI
child :combo_item_items => "PMI_items" do
child :item => "items" do
attribute :id =>"item_id"
attributes :name, :price, :description, :calories, :special_message, :redemption_value, :rating
node(:menu_id) do |me|
locals[:menu_id]
end
node(:category_id) do |i|
i.get_category_id_by_menu_id(i.id, locals[:menu_id])
end
node(:reward_points) do |rw|
rw.get_reward_points(locals[:menu_id],rw.get_category_id_by_menu_id(rw.id, locals[:menu_id]))
end
node(:is_favourite) do |item_fav|
item_fav.item_favourites.where("item_favourites.user_id = ? and item_favourites.favourite = 1", locals[:user_id]).count
end
node(:is_nexttime) do |item_nxt|
item_nxt.item_nexttimes.where("item_nexttimes.user_id = ? and item_nexttimes.nexttime = 1", locals[:user_id]).count
end
node(:review) do |item_review|
item_review.item_comments.where("item_comments.build_menu_id = ?", item_review.build_menus.first.id).count
end
#list of item_images, item_keys in PMI
child :item_photos => "item_images" do
attributes :item_id
node :image do
|i| i.photo.fullpath if i.photo
end
end
child :item_photos => "item_image_thumbnail" do
attributes :item_id
node :image do
|i| i.photo.fullpath if i.photo
end
end
child :item_keys => "item_keys" do
attributes :id, :name, :description
node :image do |i|
i.photo.fullpath if i.photo
end
end
child :item_keys => "item_key_thumbnail" do
attributes :id, :name, :description, :image_thumbnail
end
end
end
elsif locals[:item].cmi?(locals[:menu_id])
#List of items in GMI
child :combo_item_categories => "GMI_items" do
attributes :sequence, :quantity
node(:categories) do |c|
partial('category/items', :object => c.category, locals: {category_id: c.id, menu_id: locals[:menu_id], user_id: locals[:user_id]})
end
end
#List of items in PMI
child :combo_item_items => "PMI_items" do
child :item => "items" do
attribute :id =>"item_id"
attributes :name, :price, :description, :calories, :special_message, :redemption_value, :rating
node(:menu_id) do |me|
locals[:menu_id]
end
node(:category_id) do |i|
i.get_category_id_by_menu_id(i.id, locals[:menu_id])
end
node(:reward_points) do |rw|
rw.get_reward_points(locals[:menu_id],rw.get_category_id_by_menu_id(rw.id, locals[:menu_id]))
end
node(:is_favourite) do |item_fav|
item_fav.item_favourites.where("item_favourites.user_id = ? and item_favourites.favourite = 1", locals[:user_id]).count
end
node(:is_nexttime) do |item_nxt|
item_nxt.item_nexttimes.where("item_nexttimes.user_id = ? and item_nexttimes.nexttime = 1", locals[:user_id]).count
end
node(:review) do |item_review|
item_review.item_comments.where("item_comments.build_menu_id = ?", item_review.build_menus.first.id).count
end
#list of item_images, item_keys in PMI
child :item_photos => "item_images" do
attributes :item_id
node :image do
|i| i.photo.fullpath if i.photo
end
end
child :item_photos => "item_image_thumbnail" do
attributes :item_id
node :image do
|i| i.photo.fullpath if i.photo
end
end
child :item_keys => "item_keys" do
attributes :id, :name, :description
node :image do |i|
i.fullpath if i.photo
end
end
child :item_keys => "item_key_thumbnail" do
attributes :id, :name, :description, :image_thumbnail
end
end
end
end
|
class TopicsController < ApplicationController
before_action :set_topic_id, only: [:show_topic, :edit, :destroy]
before_action :set_post_id, only: [:edit_post]
def index
@project = Project.find(params[:id])
@topics = @project.topics.order(important: :desc)
end
def make_important
topic = Topic.find(params[:topic])
topic.important = true
project = Project.find(topic.project_id)
topic.save
flash[:success] = 'Tópico fixado como importante.'
redirect_to list_topics_path(project)
end
def make_not_important
topic = Topic.find(params[:topic])
topic.important = false
project = Project.find(topic.project_id)
topic.save
redirect_to list_topics_path(project)
end
def new
@topic = Topic.new
@project = params[:id]
end
def show_topic
@project = @topic.project
end
def create
@topic = Topic.new(topic_params)
@topic.user_id = current_user.id
@project = Project.find(@topic.project_id)
respond_to do |format|
if @topic.save
@project.members.where(situation: 1).each do |member|
if member.user_id != current_user.id
@topic.create_activity(:create, :owner => User.find(member.user_id))
end
end
format.html { redirect_to list_topics_path(@project), notice: 'Tópico criado com sucesso.' }
format.json { render :show, status: :created, location: @project}
else
format.html { render :new }
format.json { render json: @topic.errors, status: :unprocessable_entity }
end
end
end
def edit
end
def update
@topic = Topic.find(params[:id])
@topic.update(topic_params)
flash[:success] = 'Tópico atualizado com sucesso.'
redirect_to controller: 'topics', action: 'index', id: @topic.project.id
end
def destroy
project = @topic.project
@topic.destroy
flash[:success] = 'Tópico excluído com sucesso.'
redirect_to controller: 'topics', action: 'index', id: project.id
end
def new_post
@post = Post.new
@topic = params[:id_topic]
end
def create_post
@post = Post.new(post_params)
@post.user_id = current_user.id
topic = Topic.find(@post.topic_id)
respond_to do |format|
if @post.save
format.html { redirect_to controller: 'topics', action: 'show_topic', id: @post.topic.project.id, id_topic: @post.topic.id, notice: 'Post was successfully created.' }
format.json { render :show, status: :created, location: topic}
else
format.html { render :new }
format.json { render json: @topic.errors, status: :unprocessable_entity }
end
end
end
def edit_post
@post_id = params[:id_post]
end
def update_post
@post = Post.find(params[:id_post])
@post.update(post_params)
redirect_to controller: 'topics', action: 'show_topic', id: @post.topic.project.id, id_topic: @post.topic.id, notice: 'Post was successfully updated.'
end
def destroy_post
@post = Post.find(params[:id])
topic = @post.topic
@post.destroy
redirect_to controller: 'topics', action: 'show_topic', id_topic: topic.id, id: topic.project.id, notice: 'Post was successfully destroyed.'
end
private
# Use callbacks to share common setup or constraints between actions.
def load_activities
@activities = PublicActivity::Activity.order('created_at DESC').limit(20)
end
def set_topic
@topic = Topic.find(params[:id])
end
def set_topic_id
@topic = Topic.find(params[:id_topic])
end
def set_post_id
@post = Post.find(params[:id_post])
end
# Never trust parameters from the scary internet, only allow the white list through.
def topic_params
params.require(:topic).permit(:topic_title, :description, :important, :user_id, :project_id)
end
def post_params
params.require(:post).permit(:description, :user_id, :topic_id)
end
end
|
require 'spec_helper'
RSpec.describe Facing do
let (:valid_facing) {
Facing.new(:south)
}
let (:invalid_facing) {
Facing.new(:invalid)
}
describe 'valid?' do
context 'a valid context' do
it { expect(valid_facing.valid?).to be_truthy }
end
context 'an invalid context' do
it { expect(invalid_facing.valid?).to be_falsey }
end
end
describe 'facing' do
it { expect(valid_facing.next).to eq(:west) }
end
describe 'previous' do
it { expect(valid_facing.previous).to eq(:east) }
end
end
|
# module API
module Railsapp
module V1
class Videoapi < Grape::API
include Railsapp::V1::Defaults
format :json
resource :videoapi do
desc "Return all videos"
get "", root: :videos do
error!({:error_message => "Please provide a video id."}, 422)
end
desc "Return a video"
params do
requires :id, type: Integer, desc: "ID of the video"
end
get ":id", root: "videos" do
# Video.where(id: params[:id]).first
@video = Contents.where(id: params[:id]).first
if @video.present?
@return_data = Hash.new
@return_data['id'] = @video.id
@return_data['title'] = @video.title
@return_data['location'] = @video.location
@return_data['featured'] = @video.featured
@return_data['badges'] = @video.badges
@return_data['short_description'] = @video.short_description
@return_data['publish_status'] = @video.publish_status
if !@video.videos.empty?
if @video.videos[0].videosource == "Manual"
@return_data['video_url'] = @video.videos[0].video_file_name
@return_data['video_type'] = @video.videos[0].videosource
else
@return_data['video_url'] = @video.videos[0].youtube
@return_data['video_type'] = @video.videos[0].videosource
end
else
@return_data['video_url'] =""
@return_data['video_type'] = ""
end
error!({:success_message => "Record found",:result => @return_data }, 300)
else
error!({:error_message => "Record Could not found"}, 422)
end
end
end
end
end
end
|
module StoryboardElements
def self.table_name_prefix
'storyboard_elements_'
end
end |
class ReviewContentsController < ApplicationController
# GET /review_contents
# GET /review_contents.json
def index
@review_contents = ReviewContent.all
respond_to do |format|
format.html # index.html.erb
format.json { render json: @review_contents }
end
end
# GET /review_contents/1
# GET /review_contents/1.json
def show
@review_content = ReviewContent.find(params[:id])
respond_to do |format|
format.html # show.html.erb
format.json { render json: @review_content }
end
end
# GET /review_contents/new
# GET /review_contents/new.json
def new
@review_content = ReviewContent.new
respond_to do |format|
format.html # new.html.erb
format.json { render json: @review_content }
end
end
# GET /review_contents/1/edit
def edit
@review_content = ReviewContent.find(params[:id])
end
# POST /review_contents
# POST /review_contents.json
def create
@review_content = ReviewContent.new(params[:review_content])
respond_to do |format|
if @review_content.save
format.html { redirect_to @review_content, notice: 'Review content was successfully created.' }
format.json { render json: @review_content, status: :created, location: @review_content }
else
format.html { render action: "new" }
format.json { render json: @review_content.errors, status: :unprocessable_entity }
end
end
end
# PUT /review_contents/1
# PUT /review_contents/1.json
def update
@review_content = ReviewContent.find(params[:id])
respond_to do |format|
if @review_content.update_attributes(params[:review_content])
format.html { redirect_to @review_content, notice: 'Review content was successfully updated.' }
format.json { head :no_content }
else
format.html { render action: "edit" }
format.json { render json: @review_content.errors, status: :unprocessable_entity }
end
end
end
# DELETE /review_contents/1
# DELETE /review_contents/1.json
def destroy
@review_content = ReviewContent.find(params[:id])
@review_content.destroy
respond_to do |format|
format.html { redirect_to review_contents_url }
format.json { head :no_content }
end
end
end
|
require 'rails_helper'
describe 'frontend routes', type: :routing do
describe 'root_path' do
it 'routes to static_pages#home' do
expect(get: '/').to route_to(
controller: 'static_pages',
action: 'home',
locale: 'en'
)
end
end
describe 'courses_path' do
it 'routes to courses#index' do
expect(get: '/courses').to route_to(
controller: 'programs',
action: 'index',
locale: 'en'
)
end
it 'routes to courses#level_one' do
expect(get: '/courses/beginner-bootcamp').to route_to(
controller: 'programs',
action: 'level_one',
locale: 'en'
)
end
it 'routes to courses#level_two' do
expect(get: '/courses/intermediate-bootcamp').to route_to(
controller: 'programs',
action: 'level_two',
locale: 'en'
)
end
it 'routes to courses#level_three' do
expect(get: '/courses/advanced-bootcamp').to route_to(
controller: 'programs',
action: 'level_three',
locale: 'en'
)
end
end
describe 'enroll_path' do
it 'routes to orders#new' do
expect(get: '/enroll').to route_to(
controller: 'orders',
action: 'new',
locale: 'en'
)
end
it 'routes to orders#create' do
expect(post: '/enroll').to route_to(
controller: 'orders',
action: 'create',
locale: 'en'
)
end
it 'routes to orders#show' do
expect(get: '/enroll/1').to route_to(
controller: 'orders',
action: 'show',
id: '1',
locale: 'en'
)
end
it 'routes to orders#thanks' do
expect(get: '/enroll/1/thanks').to route_to(
controller: 'orders',
action: 'thanks',
id: '1',
locale: 'en'
)
end
it 'routes to orders#webhook' do
expect(post: '/enroll/webhook').to route_to(
controller: 'orders',
action: 'webhook',
locale: 'en'
)
end
end
describe 'team_path' do
it 'routes to static_pages#team' do
expect(get: '/team').to route_to(
controller: 'static_pages',
action: 'team',
locale: 'en'
)
end
end
describe 'blog routing' do
it 'should route to posts#index' do
describe 'blog index route' do
expect(get: '/blog').to route_to(
controller: 'posts',
action: 'index'
)
end
end
describe 'blog post route' do
it 'should route to posts#show' do
expect(get: '/blog/foobar').to route_to(
controller: 'posts',
action: 'show',
id: 'foobar',
locale: 'en'
)
end
end
end
describe 'sitemap_path' do
it 'routes to application#sitemap' do
expect(get: '/sitemap.xml').to route_to(
controller: 'application',
action: 'sitemap',
format: 'xml',
locale: 'en'
)
end
it 'routes does not route other formats than xml' do
expect(get: '/sitemap').to_not be_routable
expect(get: '/sitemap.json').to_not be_routable
end
end
end
|
require 'wsdl_mapper/svc_desc/envelope'
require 'wsdl_mapper/svc_desc/fault'
require 'wsdl_mapper/deserializers/type_directory'
module WsdlMapper
module SvcDesc
SoapTypeDirectory = WsdlMapper::Deserializers::TypeDirectory.new
FaultDeserializer = SoapTypeDirectory.register_type(['http://schemas.xmlsoap.org/soap/envelope/', 'Fault'], ::WsdlMapper::SvcDesc::Fault) do
register_prop(:code, ['http://schemas.xmlsoap.org/soap/envelope/', 'faultcode'], ['http://www.w3.org/2001/XMLSchema', 'string'])
register_prop(:string, ['http://schemas.xmlsoap.org/soap/envelope/', 'faultstring'], ['http://www.w3.org/2001/XMLSchema', 'string'])
register_prop(:actor, ['http://schemas.xmlsoap.org/soap/envelope/', 'faultactor'], ['http://www.w3.org/2001/XMLSchema', 'string'])
register_prop(:detail, ['http://schemas.xmlsoap.org/soap/envelope/', 'detail'], ['http://www.w3.org/2001/XMLSchema', 'string'])
end
EnvelopeDeserializer = SoapTypeDirectory.register_type(['http://schemas.xmlsoap.org/soap/envelope/', 'Envelope'], ::WsdlMapper::SvcDesc::Envelope) do
register_prop(:header, ['http://schemas.xmlsoap.org/soap/envelope/', 'Header'], ['http://schemas.xmlsoap.org/soap/envelope/', 'Header'])
register_prop(:body, ['http://schemas.xmlsoap.org/soap/envelope/', 'Body'], ['http://schemas.xmlsoap.org/soap/envelope/', 'Body'])
end
end
end
|
require 'yaml'
module PicMov
class Settings
SOURCE_FOLDER = "source_folder"
TARGET_FOLDER = "target_folder"
SETTINGS_FILE = "settings.yml"
def self.source_folder
settings[Settings::SOURCE_FOLDER]
end
def self.target_folder
settings[Settings::TARGET_FOLDER]
end
def self.settings
@@settings ||= load_settings
end
def self.configured?
File.exists?(settings_file_path)
end
def self.save_settings(source_folder, target_folder)
begin
File.open(settings_file_path, "w") do |f|
f.puts({
Settings::SOURCE_FOLDER => source_folder,
Settings::TARGET_FOLDER => target_folder}.to_yaml)
return "Successfully saved your settings."
end
rescue Exception => e
return "An error occurred while saving your settings: #{e}."
end
end
private
def self.settings_file_path
if RUBY_PLATFORM =~ /win32/
if ENV['USERPROFILE']
if File.exist?(File.join(File.expand_path(ENV['USERPROFILE']), "Application Data"))
user_data_directory = File.join File.expand_path(ENV['USERPROFILE']), "Application Data", "PicMov"
else
user_data_directory = File.join File.expand_path(ENV['USERPROFILE']), "PicMov"
end
else
user_data_directory = File.join File.expand_path(Dir.getwd), "data"
end
else
user_data_directory = File.expand_path(File.join("~", ".picmov"))
end
unless File.exist?(user_data_directory)
Dir.mkdir(user_data_directory)
end
return File.join(user_data_directory, Settings::SETTINGS_FILE)
end
def self.load_settings
if configured?
@@settings = YAML.load_file(settings_file_path)
end
end
end
end#module PicMov |
# frozen_string_literal: true
require 'rgeo/geo_json'
module GeoJSON
class Decoder
class MissingGeometry < StandardError; end
def call(json)
RGeo::GeoJSON.decode(json).tap do |maybe_geo|
raise MissingGeometry, 'failed to decode into known geometry' if maybe_geo.nil?
end
end
end
end
|
# frozen_string_literal: true
class UserMailer < ActionMailer::Base
include LogWrapper
LOG_TAG = "UserMailer"
default :from => '"MyLibraryNYC Admin" <no-reply@mylibrarynyc.org>'
##
# Let the user know they've successfully unsubscribed from regular notification emails.
# NOTE: Does not get used at this time.
def unsubscribe(user)
begin
@user = user
mail(:to => @user.contact_email, :subject => "You have now unsubscribed from MyLibraryNyc.")
rescue => e
# something went wrong. perhaps the user isn't set properly, or maybe the email couldn't be sent out.
Rails.logger.error("#{LOG_TAG}.unsubscribe: ")
LogWrapper.log('ERROR', {
'message' => "Cannot send unsubscribe confirmation email. Backtrace=#{e.backtrace}.",
'method' => 'UserMailer unsubscribe'
})
raise
end
end
end
|
class PersonalOrdersController < ApplicationController
def index
redirect_to order_path(params[:order_id])
end
def new
@personal_order = PersonalOrder.new
@parent_order = get_parent_order
end
def create
@parent_order = get_parent_order
@personal_order = PersonalOrder.new(personal_order_params)
@personal_order.order_id = params[:order_id]
@personal_order.user_id = current_user.id
@personal_order.name = current_user.name
if !@personal_order.valid?
flash[:notice] = @personal_order.errors.full_messages;
render :new
else
# the following is an adjustment on the price
@personal_order.price = (@personal_order.price).round(2)
if @personal_order.save
flash[:notice] = 'saved!'
redirect_to order_path(:id => params[:order_id])
else
flash[:notice] = @personal_order.errors.full_messages;
render :new
end
end
end
def show
@personal_order = PersonalOrder.new
@order_ref = params[:id]
end
def destroy
@remove_order = PersonalOrder.find(params[:order_id])
@remove_order.destroy
flash[:notice] = "Cancelled your order!"
redirect_to order_path(:id => params[:id])
end
private
def personal_order_params
params.require(:personal_order).permit(:name, :price, :items)
end
def get_parent_order
Order.find(params[:order_id])
end
end
|
require 'rails_helper'
RSpec.describe User, type: :model do
context 'validation tests' do
let(:user) { build(:user) }
it 'ensures email is present' do
user.email = nil
expect(user.save).to eq(false)
end
it 'ensures password is present' do
user.password = nil
expect(user.save).to eq(false)
end
it 'should save succesfully' do
expect(user.save).to eq(true)
end
end
end
|
class ShortResponse < ApplicationRecord
belongs_to :short_question
belongs_to :organization
validates :response, :presence => true
end
|
ActionView::Helpers::FormBuilder.class_eval do
# YAML TAGS
# generates form tags that work with the YAML CSS-Framework
def yaml_text_field(attr, label = nil)
yaml_tag self.text_field(attr), self.label(attr, label), has_errors(attr)
end
def yaml_email_field(attr, label = nil)
yaml_tag self.email_field(attr), self.label(attr, label), has_errors(attr)
end
def yaml_file_field(attr, label = nil)
yaml_tag self.file_field(attr), self.label(attr, label), has_errors(attr)
end
def yaml_number_field(attr, label = nil)
yaml_tag self.number_field(attr), self.label(attr, label), has_errors(attr)
end
def yaml_text_area(attr, params = {}, label = nil )
yaml_tag self.text_area(attr, params), self.label(attr, label), has_errors(attr)
end
def yaml_password_field(attr, label = nil)
yaml_tag self.password_field(attr), self.label(attr, label), has_errors(attr)
end
def yaml_checkbox(attr, label = nil )
yaml_tag self.check_box(attr), self.label(attr, label), has_errors(attr), 'check'
end
def yaml_select(attr, options, tag_options = {}, label = nil )
yaml_tag self.select(attr, options, tag_options), self.label(attr, label), has_errors(attr), 'select'
end
def yaml_multi_select(attr, select_options, options = {}, tag_options = {}, label = nil )
options.merge!({:selected => f.object.send(attr+"_ids")})
tag_options.merge!({:multiple=>true, :size=>6, :name => "#{f.object.class.to_s.downcase}[#{attr}_ids][]"})
yaml_tag collection_select(self.object.class.to_s.downcase, attr.pluralize, select_options, :id, :to_s, options, tag_options ), self.label(attr, label), has_errors(attr), 'select'
end
def yaml_submit(name = nil)
"<div class='type-button'>
#{self.submit name, :class => 'submit' }
</div>".html_safe
end
def yaml_tag(tag, label, error = false, type = 'text')
"<div class='type-#{type} #{ 'error' if error }'>
#{label}
#{tag}
</div>".html_safe
end
def has_errors(attr)
return !self.object.errors[attr].empty?
end
end
|
require 'active_model'
module Baison
class Base
include ActiveModel::Model
include ActiveModel::Serializers::JSON
class_attribute :resource
class_attribute :params
attr_accessor :logger
def initialize(args)
@logger = Logger.new(STDOUT)
super args
end
def save
json = self.class.connection.post(self.resource, {}, self.as_json)
self.class.new(json)
end
def attributes
raise StandardError("define your model's attributes,return a hash")
end
class << self
def find_all(args)
find(args)
end
def find_one(args)
args.merge!({page_size: 1})
find(args).first
end
# @return [Baison::Connection]
def connection
Connection.new(self.params)
end
protected
def find(options)
a = Array.new
json = connection.post(self.resource, options)
if json['status'].to_s != '1'
raise ::StandardError.new(json)
end
begin
data = json['data']['data']
rescue
raise ::StandardError.new(json)
end
if block_given?
a = yield data
else
data.each do |row|
a << self.new(row)
end
end
a
end
end
def _assign_attribute(k, v)
if respond_to?("#{k}=")
public_send("#{k}=", v)
else
# raise UnknownAttributeError.new(self, k)
end
end
end
end
|
class AddImageNameToPaintings < ActiveRecord::Migration
def change
add_column :paintings, :image_name, :string
end
end
|
class CollisionDetector
attr_reader :moving_element, :static_elements
def initialize(moving_element:, static_elements:)
@moving_element = moving_element
@static_elements = static_elements
end
def detect!
close_elements = static_elements.reject! do |element|
G::distance(
moving_element.x, moving_element.y,
element.x, element.y
) < 35
end
moving_element.collide if close_elements
end
end
|
#!/usr/bin/env ruby
gem = Gem::Specification::load("rumrunner.gemspec")
pkg = "pkg/#{gem.full_name}.gem"
rum gem.name do
tag gem.version.to_s
env :RUBY_VERSION => ENV["RUBY_VERSION"] || "latest"
stage :install
stage :test => :install
stage :build => :test
artifact pkg => :build
desc "Push `#{pkg}` to rubygems.org"
task :push => pkg do
sh "gem", "push", pkg
end
default pkg
end
|
class ApplicationController < ActionController::Base
protect_from_forgery with: :exception
before_action :set_locale
def set_locale
I18n.locale = params[:lang] || I18n.default_locale
end
def default_url_options(options = {})
{ lang: I18n.locale == I18n.default_locale ? nil : I18n.locale }
end
def user_preferred_language
http_accept_language.compatible_language_from(I18n.available_locales)
end
end
|
# Create execution history table
class CreateExecutionHistories < ActiveRecord::Migration[4.2]
def change
create_table :execution_histories do |t|
t.references :user, null: false
t.foreign_key :users, on_delete: :cascade, on_update: :cascade
t.references :notebook, null: false
t.foreign_key :notebooks, on_delete: :cascade, on_update: :cascade
t.boolean :known_cell
t.boolean :unknown_cell
t.timestamps null: false
end
end
end
|
# Customer User Type
#
# has_many tickets
class Customer < User
has_many :tickets
default_scope -> {includes(:user_type).where(user_types: {name: 'customer'})}
end
|
#!/usr/bin/ruby -rubygems
# encoding: utf-8
require_relative 'lib/build_fojas'
puts 'Iniciando Comanda: fojas con salsa de FOXML, término medio.'
begin
if ARGV.length != 1
raise ArgumentError.new "Se esperaba solo un argumento (la ruta al archivo INI de configuración para el proceso)."
exit
else
ini_file = ARGV[0]
raise IOError.new "Archivo inexistente: #{ini_file}" unless File.exists? ini_file
end
rescue Exception => e
puts "#{e.class}: #{e.message}"
end
f = BuildFojas.new ini_file
f.do_build |
require 'spec_helper'
describe ProductsController do
let(:authenticated_user) {
double("authenticated user", {
:id => 42,
})
}
describe 'POST #create', wip: true do
before do
subject.stub(current_user: authenticated_user)
end
let(:valid_attributes) { {
name: "Foo Product",
description: "Bar Baz Bat",
price: 123,
inventory: 7,
} }
let(:invalid_attributes) { valid_attributes.except(:name) }
context 'with valid attributes' do
it 'should create a new product' do
expect{
post :create, product: valid_attributes
}.to change(Product, :count).by(1)
end
it "should associate the new product with the current user" do
post :create, product: valid_attributes
expect(Product.last.user_id).to eq(authenticated_user.id)
end
it "redirects to the new product" do
post :create, product: valid_attributes
expect(response).to redirect_to("/products/#{Product.last.id}")
end
end
context 'with invalid attributes' do
it "should not create a new product" do
expect{
post :create, product: invalid_attributes
}.not_to change(Product, :count)
end
it 'redirects with a flash message' do
post :create, product: invalid_attributes
expect(flash[:notice]).to include('There was an error')
expect(response).to redirect_to("/products/new")
end
end
end
end |
class Comment < ApplicationRecord
belongs_to :commentable, polymorphic: true
belongs_to :owner, class_name: "User", optional: true
belongs_to :report, optional: true
before_create :set_commentable_type
validates :body, presence: true
validates :report, presence: {unless: -> { commentable_type == "Activity" && commentable.programme? }}
scope :with_commentables, -> {
joins("left outer join activities on activities.id = comments.commentable_id AND comments.commentable_type = 'Activity'")
.joins("left outer join transactions AS refunds on refunds.id = comments.commentable_id AND comments.commentable_type = 'Refund'")
.joins("left outer join transactions AS adjustments on adjustments.id = comments.commentable_id AND comments.commentable_type = 'Adjustment'")
.joins("left outer join transactions AS actuals on actuals.id = comments.commentable_id AND comments.commentable_type = 'Actual'")
}
scope :for_activity, ->(activity) {
with_commentables
.where("refunds.parent_activity_id = :activity_id OR
adjustments.parent_activity_id = :activity_id OR
activities.id = :activity_id OR
actuals.parent_activity_id = :activity_id", {activity_id: activity.id})
}
def set_commentable_type
self.commentable_type = commentable.class.to_s
end
def associated_activity
return commentable if commentable_type == "Activity"
# Expected other values of commentable_type Refund, Adjustment and Actual
commentable.parent_activity
end
end
|
###################################
#
# EVM Automate Method: InspectMe
#
# Notes: Dump the objects in storage to the automation.log
#
###################################
begin
@method = 'InspectMe'
$evm.log("info", "#{@method} - EVM Automate Method Started")
# Turn of verbose logging
@debug = true
#########################
#
# Method: dumpRoot
# Description: Dump Root information
#
##########################
def dumpRoot
$evm.log("info", "#{@method} - Root:<$evm.root> Begin Attributes")
$evm.root.attributes.sort.each { |k, v| $evm.log("info", "#{@method} - Root:<$evm.root> Attributes - #{k}: #{v}")}
$evm.log("info", "#{@method} - Root:<$evm.root> End Attributes")
$evm.log("info", "")
end
#########################
#
# Method: dumpServer
# Inputs: $evm.root['miq_server']
# Description: Dump MIQ Server information
#
##########################
def dumpServer
$evm.log("info","#{@method} - Server:<#{$evm.root['miq_server'].name}> Begin Attributes")
$evm.root['miq_server'].attributes.sort.each { |k, v| $evm.log("info", "#{@method} - Server:<#{$evm.root['miq_server'].name}> Attributes - #{k}: #{v.inspect}")}
$evm.log("info","#{@method} - Server:<#{$evm.root['miq_server'].name}> End Attributes")
$evm.log("info", "")
end
#########################
#
# Method: dumpUser
# Inputs: $evm.root['user']
# Description: Dump User information
#
##########################
def dumpUser
user = $evm.root['user']
unless user.nil?
$evm.log("info","#{@method} - User:<#{user.name}> Begin Attributes [user.attributes]")
user.attributes.sort.each { |k, v| $evm.log("info", "#{@method} - User:<#{user.name}> Attributes - #{k}: #{v.inspect}")}
$evm.log("info","#{@method} - User:<#{user.name}> End Attributes [user.attributes]")
$evm.log("info", "")
$evm.log("info","#{@method} - User:<#{user.name}> Begin Associations [user.associations]")
user.associations.sort.each { |assc| $evm.log("info", "#{@method} - User:<#{user.name}> Associations - #{assc}")}
$evm.log("info","#{@method} - User:<#{user.name}> End Associations [user.associations]")
$evm.log("info","")
unless user.tags.nil?
$evm.log("info","#{@method} - User:<#{user.name}> Begin Tags [user.tags]")
user.tags.sort.each { |tag_element| tag_text = tag_element.split('/'); $evm.log("info", "#{@method} - User:<#{user.name}> Category:<#{tag_text.first.inspect}> Tag:<#{tag_text.last.inspect}>")}
$evm.log("info","#{@method} - User:<#{user.name}> End Tags [user.tags]")
$evm.log("info","")
end
#$evm.log("info","#{@method} - User:<#{user.name}> Begin Virtual Columns [user.virtual_column_names]")
#user.virtual_column_names.sort.each { |vcn| $evm.log("info", "#{@method} - User:<#{user.name}> Virtual Columns - #{vcn}: #{user.send(vcn).inspect}")}
#$evm.log("info","#{@method} - User:<#{user.name}> End Virtual Columns [user.virtual_column_names]")
#$evm.log("info","")
end
end
#########################
#
# Method: dumpGroup
# Inputs: $evm.root['user'].miq_group
# Description: Dump User's Group information
#
##########################
def dumpGroup
user = $evm.root['user']
unless user.nil?
miq_group = user.miq_group
unless miq_group.nil?
$evm.log("info","#{@method} - Group:<#{miq_group.description}> Begin Attributes [miq_group.attributes]")
miq_group.attributes.sort.each { |k, v| $evm.log("info", "#{@method} - Group:<#{miq_group.description}> Attributes - #{k}: #{v.inspect}")} unless $evm.root['user'].miq_group.nil?
$evm.log("info","#{@method} - Group:<#{miq_group.description}> End Attributes [miq_group.attributes]")
$evm.log("info", "")
$evm.log("info","#{@method} - Group:<#{miq_group.description}> Begin Associations [miq_group.associations]")
miq_group.associations.sort.each { |assc| $evm.log("info", "#{@method} - Group:<#{miq_group.description}> Associations - #{assc}")}
$evm.log("info","#{@method} - Group:<#{miq_group.description}> End Associations [miq_group.associations]")
$evm.log("info","")
unless miq_group.tags.nil?
$evm.log("info","#{@method} - Group:<#{miq_group.description}> Begin Tags [miq_group.tags]")
miq_group.tags.sort.each { |tag_element| tag_text = tag_element.split('/'); $evm.log("info", "#{@method} - Group:<#{miq_group.description}> Category:<#{tag_text.first.inspect}> Tag:<#{tag_text.last.inspect}>")}
$evm.log("info","#{@method} - Group:<#{miq_group.description}> End Tags [miq_group.tags]")
$evm.log("info","")
end
$evm.log("info","#{@method} - Group:<#{miq_group.description}> Begin Virtual Columns [miq_group.virtual_column_names]")
miq_group.virtual_column_names.sort.each { |vcn| $evm.log("info", "#{@method} - Group:<#{miq_group.description}> Virtual Columns - #{vcn}: #{miq_group.send(vcn).inspect}")}
$evm.log("info","#{@method} - Group:<#{miq_group.description}> End Virtual Columns [miq_group.virtual_column_names]")
$evm.log("info","")
end
end
end
#########################
#
# Method: dumpHost
# Inputs: $evm.root['host']
# Description: Dump Host information
#
##########################
def dumpHost(host)
$evm.log("info","#{@method} - Host:<#{host.name}> Begin Attributes [host.attributes]")
host.attributes.sort.each { |k, v| $evm.log("info", "#{@method} - Host:<#{host.name}> Attributes - #{k}: #{v.inspect}")}
$evm.log("info","#{@method} - Host:<#{host.name}> End Attributes [host.attributes]")
$evm.log("info","")
$evm.log("info","#{@method} - Host:<#{host.name}> Begin Associations [host.associations]")
host.associations.sort.each { |assc| $evm.log("info", "#{@method} - Host:<#{host.name}> Associations - #{assc}")}
$evm.log("info","#{@method} - Host:<#{host.name}> End Associations [host.associations]")
$evm.log("info","")
$evm.log("info","#{@method} - Host:<#{host.name}> Begin Hardware [host.hardware]")
host.hardware.attributes.each { |k,v| $evm.log("info", "#{@method} - Host:<#{host.name}> Hardware - #{k}: #{v.inspect}")}
$evm.log("info","#{@method} - Host:<#{host.name}> End Hardware [host.hardware]")
$evm.log("info","")
$evm.log("info","#{@method} - Host:<#{host.name}> Begin Lans [host.lans]")
host.lans.each { |lan| lan.attributes.sort.each { |k,v| $evm.log("info", "#{@method} - Host:<#{host.name}> Lan:<#{lan.name}> - #{k}: #{v.inspect}")}}
$evm.log("info","#{@method} - Host:<#{host.name}> End Lans [host.lans]")
$evm.log("info","")
$evm.log("info","#{@method} - Host:<#{host.name}> Begin Switches [host.switches]")
host.switches.each { |switch| switch.attributes.sort.each { |k,v| $evm.log("info", "#{@method} - Host:<#{host.name}> Swtich:<#{switch.name}> - #{k}: #{v.inspect}")}}
$evm.log("info","#{@method} - Host:<#{host.name}> End Switches [host.switches]")
$evm.log("info","")
$evm.log("info","#{@method} - Host:<#{host.name}> Begin Operating System [host.operating_system]")
host.operating_system.attributes.sort.each { |k, v| $evm.log("info", "#{@method} - Host:<#{host.name}> Operating System - #{k}: #{v.inspect}")}
$evm.log("info","#{@method} - Host:<#{host.name}> End Operating System [host.operating_system]")
$evm.log("info","")
$evm.log("info","#{@method} - Host:<#{host.name}> Begin Guest Applications [host.guest_applications]")
host.guest_applications.each { |guest_app| guest_app.attributes.sort.each { |k, v| $evm.log("info", "#{@method} - Host:<#{host.name}> Guest Application:<#{guest_app.name}> - #{k}: #{v.inspect}")}}
$evm.log("info","#{@method} - Host:<#{host.name}> End Guest Applications [host.guest_applications]")
$evm.log("info","")
unless host.tags.nil?
$evm.log("info","#{@method} - Host:<#{host.name}> Begin Tags [host.tags]")
host.tags.sort.each { |tag_element| tag_text = tag_element.split('/'); $evm.log("info", "#{@method} - Host:<#{host.name}> Category:<#{tag_text.first.inspect}> Tag:<#{tag_text.last.inspect}>")}
$evm.log("info","#{@method} - Host:<#{host.name}> End Tags [host.tags]")
$evm.log("info","")
end
$evm.log("info","#{@method} - Host:<#{host.name}> Begin Virtual Columns [host.virtual_column_names]")
host.virtual_column_names.sort.each { |vcn| $evm.log("info", "#{@method} - Host:<#{host.name}> Virtual Columns - #{vcn}: #{host.send(vcn).inspect}")}
$evm.log("info","#{@method} - Host:<#{host.name}> End Virtual Columns [host.virtual_column_names]")
$evm.log("info", "")
end
#########################
#
# Method: dumpVM
# Inputs: $evm.root['vm']
# Description: Dump VM information
#
##########################
def dumpVM(vm)
$evm.log("info","#{@method} - VM:<#{vm.name}> Begin Attributes [vm.attributes]")
vm.attributes.sort.each { |k, v| $evm.log("info", "#{@method} - VM:<#{vm.name}> Attributes - #{k}: #{v.inspect}")}
$evm.log("info","#{@method} - VM:<#{vm.name}> End Attributes [vm.attributes]")
$evm.log("info","")
$evm.log("info","#{@method} - VM:<#{vm.name}> Begin Associations [vm.associations]")
vm.associations.sort.each { |assc| $evm.log("info", "#{@method} - VM:<#{vm.name}> Associations - #{assc}")}
$evm.log("info","#{@method} - VM:<#{vm.name}> End Associations [vm.associations]")
$evm.log("info","")
$evm.log("info","#{@method} - VM:<#{vm.name}> Begin Hardware Attributes [vm.hardware]")
vm.hardware.attributes.each { |k,v| $evm.log("info", "#{@method} - VM:<#{vm.name}> Hardware - #{k}: #{v.inspect}")}
$evm.log("info","#{@method} - VM:<#{vm.name}> End Hardware Attributes [vm.hardware]")
$evm.log("info","")
$evm.log("info","#{@method} - VM:<#{vm.name}> Begin Hardware Associations [vm.hardware.associations]")
vm.hardware.associations.sort.each { |assc| $evm.log("info", "#{@method} - VM:<#{vm.name}> hardware Associations - #{assc}")}
$evm.log("info","#{@method} - VM:<#{vm.name}> End hardware Associations [vm.hardware.associations]")
$evm.log("info","")
$evm.log("info","#{@method} - VM:<#{vm.name}> Begin Neworks [vm.hardware.nics]")
vm.hardware.nics.each { |nic| nic.attributes.sort.each { |k,v| $evm.log("info", "#{@method} - VM:<#{vm.name}> VLAN:<#{nic.device_name}> - #{k}: #{v.inspect}")}}
$evm.log("info","#{@method} - VM:<#{vm.name}> End Networks [vm.hardware.nics]")
$evm.log("info","")
unless vm.ext_management_system.nil?
$evm.log("info","#{@method} - VM:<#{vm.name}> Begin EMS [vm.ext_management_system]")
vm.ext_management_system.attributes.sort.each { |ems_k, ems_v| $evm.log("info", "#{@method} - VM:<#{vm.name}> EMS:<#{vm.ext_management_system.name}> #{ems_k} - #{ems_v.inspect}")}
$evm.log("info","#{@method} - VM:<#{vm.name}> End EMS [vm.ext_management_system]")
$evm.log("info","")
end
unless vm.owner.nil?
$evm.log("info","#{@method} - VM:<#{vm.name}> Begin Owner [vm.owner]")
vm.owner.attributes.each { |k,v| $evm.log("info", "#{@method} - VM:<#{vm.name}> Owner - #{k}: #{v.inspect}")}
$evm.log("info","#{@method} - VM:<#{vm.name}> End Owner [vm.owner]")
$evm.log("info","")
end
unless vm.operating_system.nil?
$evm.log("info","#{@method} - VM:<#{vm.name}> Begin Operating System [vm.operating_system]")
vm.operating_system.attributes.sort.each { |k, v| $evm.log("info", "#{@method} - VM:<#{vm.name}> Operating System - #{k}: #{v.inspect}")}
$evm.log("info","#{@method} - VM:<#{vm.name}> End Operating System [vm.operating_system]")
$evm.log("info","")
end
unless vm.guest_applications.nil?
$evm.log("info","#{@method} - VM:<#{vm.name}> Begin Guest Applications [vm.guest_applications]")
vm.guest_applications.each { |guest_app| guest_app.attributes.sort.each { |k, v| $evm.log("info", "#{@method} - VM:<#{vm.name}> Guest Application:<#{guest_app.name}> - #{k}: #{v.inspect}")}} unless vm.guest_applications.nil?
$evm.log("info","#{@method} - VM:<#{vm.name}> End Guest Applications [vm.guest_applications]")
$evm.log("info","")
end
unless vm.snapshots.nil?
$evm.log("info","#{@method} - VM:<#{vm.name}> Begin Snapshots [vm.snapshots]")
vm.snapshots.each { |ss| ss.attributes.sort.each { |k, v| $evm.log("info", "#{@method} - VM:<#{vm.name}> Snapshot:<#{ss.name}> - #{k}: #{v.inspect}")}} unless vm.snapshots.nil?
$evm.log("info","#{@method} - VM:<#{vm.name}> End Snapshots [vm.snapshots]")
$evm.log("info","")
end
unless vm.storage.nil?
$evm.log("info","#{@method} - VM:<#{vm.name}> Begin VM Storage [vm.storage]")
vm.storage.attributes.sort.each { |stor_k, stor_v| $evm.log("info", "#{@method} - VM:<#{vm.name}> Storage:<#{vm.storage.name}> #{stor_k} - #{stor_v.inspect}")}
$evm.log("info","#{@method} - VM:<#{vm.name}> End VM Storage [vm.storage]")
$evm.log("info","")
end
unless vm.tags.nil?
$evm.log("info","#{@method} - VM:<#{vm.name}> Begin Tags [vm.tags]")
vm.tags.sort.each { |tag_element| tag_text = tag_element.split('/'); $evm.log("info", "#{@method} - VM:<#{vm.name}> Category:<#{tag_text.first.inspect}> Tag:<#{tag_text.last.inspect}>")}
$evm.log("info","#{@method} - VM:<#{vm.name}> End Tags [vm.tags]")
$evm.log("info","")
end
$evm.log("info","#{@method} - VM:<#{vm.name}> Begin Virtual Columns [vm.virtual_column_names]")
vm.virtual_column_names.sort.each { |vcn| $evm.log("info", "#{@method} - VM:<#{vm.name}> Virtual Columns - #{vcn}: #{vm.send(vcn).inspect}")}
$evm.log("info","#{@method} - VM:<#{vm.name}> End Virtual Columns [vm.virtual_column_names]")
$evm.log("info","")
end
#########################
#
# Method: dumpCluster
# Inputs: $evm.root['ems_cluster']
# Description: Dump Cluster information
#
##########################
def dumpCluster(cluster)
$evm.log("info","#{@method} - Cluster:<#{cluster.name}> Begin Attributes [cluster.attributes]")
cluster.attributes.sort.each { |k, v| $evm.log("info", "#{@method} - Cluster:<#{cluster.name}> Attributes - #{k}: #{v.inspect}")}
$evm.log("info","#{@method} - Cluster:<#{cluster.name}> End Attributes [cluster.attributes]")
$evm.log("info","")
$evm.log("info","#{@method} - Cluster:<#{cluster.name}> Begin Associations [cluster.associations]")
cluster.associations.sort.each { |assc| $evm.log("info", "#{@method} - Cluster:<#{cluster.name}> Associations - #{assc}")}
$evm.log("info","#{@method} - Cluster:<#{cluster.name}> End Associations [cluster.associations]")
$evm.log("info","")
unless cluster.tags.nil?
$evm.log("info","#{@method} - Cluster:<#{cluster.name}> Begin Tags [cluster.tags]")
cluster.tags.sort.each { |tag_element| tag_text = tag_element.split('/'); $evm.log("info", "#{@method} - Cluster:<#{cluster.name}> Category:<#{tag_text.first.inspect}> Tag:<#{tag_text.last.inspect}>")}
$evm.log("info","#{@method} - Cluster:<#{cluster.name}> End Tags [cluster.tags]")
$evm.log("info","")
end
$evm.log("info","#{@method} - Cluster:<#{cluster.name}> Begin Virtual Columns [cluster.virtual_column_names]")
cluster.virtual_column_names.sort.each { |vcn| $evm.log("info", "#{@method} - Cluster:<#{cluster.name}> Virtual Columns - #{vcn}: #{cluster.send(vcn)}")}
$evm.log("info","#{@method} - Cluster:<#{cluster.name}> End Virtual Columns [cluster.virtual_column_names]")
$evm.log("info","")
end
#########################
#
# Method: dumpEMS
# Inputs: $evm.root['ext_managaement_system']
# Description: Dump EMS information
#
##########################
def dumpEMS(ems)
$evm.log("info","#{@method} - EMS:<#{ems.name}> Begin Attributes [ems.attributes]")
ems.attributes.sort.each { |k, v| $evm.log("info", "#{@method} - EMS:<#{ems.name}> Attributes - #{k}: #{v.inspect}")}
$evm.log("info","#{@method} - EMS:<#{ems.name}> End Attributes [ems.attributes]")
$evm.log("info","")
$evm.log("info","#{@method} - EMS:<#{ems.name}> Begin Associations [ems.associations]")
ems.associations.sort.each { |assc| $evm.log("info", "#{@method} - EMS:<#{ems.name}> Associations - #{assc}")}
$evm.log("info","#{@method} - EMS:<#{ems.name}> End Associations [ems.associations]")
$evm.log("info","")
$evm.log("info","#{@method} - EMS:<#{ems.name}> Begin EMS Folders [ems.ems_folders]")
ems.ems_folders.each { |ef| ef.attributes.sort.each { |k,v| $evm.log("info", "#{@method} - EMS:<#{ems.name}> EMS Folder:<#{ef.name}> #{k}: #{v.inspect}")}}
$evm.log("info","#{@method} - EMS:<#{ems.name}> End EMS Folders [ems.ems_folders]")
$evm.log("info","")
unless ems.tags.nil?
$evm.log("info","#{@method} - EMS:<#{ems.name}> Begin Tags [ems.tags]")
ems.tags.sort.each { |tag_element| tag_text = tag_element.split('/'); $evm.log("info", "#{@method} - EMS:<#{ems.name}> Category:<#{tag_text.first.inspect}> Tag:<#{tag_text.last.inspect}>")}
$evm.log("info","#{@method} - EMS:<#{ems.name}> End Tags [ems.tags]")
$evm.log("info","")
end
$evm.log("info","#{@method} - EMS:<#{ems.name}> Begin Virtual Columns [ems.virtual_column_names]")
ems.virtual_column_names.sort.each { |vcn| $evm.log("info", "#{@method} - EMS:<#{ems.name}> Virtual Columns - #{vcn}: #{ems.send(vcn)}")}
$evm.log("info","#{@method} - EMS:<#{ems.name}> End Virtual Columns [ems.virtual_column_names]")
$evm.log("info","")
end
#########################
#
# Method: dumpStorage
# Inputs: $evm.root['storage']
# Description: Dump Storage information
#
##########################
def dumpStorage(storage)
$evm.log("info","#{@method} - Storage:<#{storage.name}> Begin Attributes [storage.attributes]")
storage.attributes.sort.each { |k, v| $evm.log("info", "#{@method} - Storage:<#{storage.name}> Attributes - #{k}: #{v.inspect}")}
$evm.log("info","#{@method} - Storage:<#{storage.name}> End Attributes [storage.attributes]")
$evm.log("info","")
$evm.log("info","#{@method} - Storage:<#{storage.name}> Begin Associations [storage.associations]")
storage.associations.sort.each { |assc| $evm.log("info", "#{@method} - Storage:<#{storage.name}> Associations - #{assc}")}
$evm.log("info","#{@method} - Storage:<#{storage.name}> End Associations [storage.associations]")
$evm.log("info","")
unless storage.tags.nil?
$evm.log("info","#{@method} - Storage:<#{storage.name}> Begin Tags [storage.tags]")
storage.tags.sort.each { |tag_element| tag_text = tag_element.split('/'); $evm.log("info", "#{@method} - Storage:<#{storage.name}> Category:<#{tag_text.first.inspect}> Tag:<#{tag_text.last.inspect}>")}
$evm.log("info","#{@method} - Storage:<#{storage.name}> End Tags [storage.tags]")
$evm.log("info","")
end
$evm.log("info","#{@method} - Storage:<#{storage.name}> Begin Virtual Columns [storage.virtual_column_names]")
storage.virtual_column_names.sort.each { |vcn| $evm.log("info", "#{@method} - Storage:<#{storage.name}> Virtual Columns - #{vcn}: #{storage.send(vcn)}")}
$evm.log("info","#{@method} - Storage:<#{storage.name}> End Virtual Columns [storage.virtual_column_names]")
$evm.log("info","")
end
# List the types of object we will try to detect
obj_types = %w{ vm host storage ems_cluster ext_management_system }
obj_type = $evm.root.attributes.detect { |k,v| obj_types.include?(k)}
# dump root object attributes
dumpRoot
# dump miq_server object attributes
dumpServer
# dump user attributes
dumpUser
# dump miq_group attributes
dumpGroup
# If obj_type is NOT nil
unless obj_type.nil?
rootobj = obj_type.first
obj = obj_type.second
$evm.log("info", "#{@method} - Detected Object:<#{rootobj}>")
$evm.log("info","")
case rootobj
when 'host' then dumpHost(obj)
when 'vm' then dumpVM(obj)
when 'ems_cluster' then dumpCluster(obj)
when 'ext_management_system' then dumpEMS(obj)
when 'storage' then dumpStorage(obj)
end
end
#
# Exit method
#
$evm.log("info", "#{@method} - EVM Automate Method Ended")
exit MIQ_OK
#
# Set Ruby rescue behavior
#
rescue => err
$evm.log("error", "#{@method} - [#{err}]\n#{err.backtrace.join("\n")}")
exit MIQ_ABORT
end
|
# copied from: http://lucatironi.net/tutorial/2015/08/23/rails_api_authentication_warden/?utm_source=rubyweekly&utm_medium=email
require 'rails_helper'
RSpec.shared_examples 'api_controller' do
describe 'rescues from ActiveRecord::RecordNotFound' do
context 'on GET #show' do
before { get :show, { id: 'not-existing', format: :json } }
it { expect(response.status).to eq(404) }
it { expect(response.body).to be_blank }
end
context 'on PUT #update' do
before { put :update, { id: 'not-existing', format: :json } }
it { expect(response.status).to eq(404) }
it { expect(response.body).to be_blank }
end
context 'on DELETE #destroy' do
before { delete :destroy, { id: 'not-existing', format: :json } }
it { expect(response.status).to eq(404) }
it { expect(response.body).to be_blank }
end
end
describe 'rescues from ActionController::ParameterMissing' do
context 'on POST #create' do
before { post :create,
{ wrong_params: { random_params: :random },
format: :json }
}
it { expect(response.status).to eq(422) }
it { expect(response.body).to match(/error/) }
end
end
describe "responds to OPTIONS requests to return CORS headers" do
before { process :index, 'OPTIONS' }
context "CORS requests" do
it "returns the Access-Control-Allow-Origin header to allow CORS from anywhere" do
expect(response.headers['Access-Control-Allow-Origin']).to eq('*')
end
it "returns general HTTP methods through CORS (GET/POST/PUT/DELETE)" do
%w{GET POST PUT DELETE}.each do |method|
expect(response.headers['Access-Control-Allow-Methods']).to include(method)
end
end
it "returns the allowed headers" do
%w{Content-Type Accept X-User-Email X-Auth-Token}.each do |header|
expect(response.headers['Access-Control-Allow-Headers']).to include(header)
end
end
end
end
end
|
class AddSubcategoryToCategory < ActiveRecord::Migration[6.1]
def change
add_reference :categories, :subcategory, null: false, foreign_key: {to_table: :categories}, index: true
end
end
|
class ClassMaterial < ApplicationRecord
belongs_to :lecture
has_one_attached :upload
end
|
module Carnivore
def diet
puts 'meat'
end
def teeth
puts 'sharp'
end
end
module Herbivore
def diet
puts 'plant'
end
def teeth
puts 'flat'
end
end
module Nocturnal
def sleep_time
puts 'day'
end
def awake_time
puts 'night'
end
end
module Diurnal
def sleep_time
puts "night"
end
def awake_time
puts "day"
end
end
def new_animal(diet, awake)
animal = Object.new
if diet == :meat
animal.extend Carnivore
else
animal.extend Herbivore
end
if awake == :day
animal.extend Diurnal
else
animal.extend Nocturnal
end
end
#集合类,
class CompositeBase
attr_reader :name
def initialize name
@name = name
end
def self.memeber_of composite_name
attribute_name = "parent_#{composite_name}"
# p instance_methods.include? attribute_name.to_sym #have to use to_sym
raise 'Method redefinition' if instance_methods.include? attribute_name.to_sym
#in `memeber_of': Method redefinition (RuntimeError)
code = %Q{
attr_accessor :#{attribute_name}
}
class_eval code
end
def self.composite_of composite_name
memeber_of composite_name
#need evaluate, need use string of code:
code = %Q{
def sub_#{composite_name}s
@sub_#{composite_name}s ||= []
@sub_#{composite_name}s
end
def add_sub_#{composite_name}(child)
return if sub_#{composite_name}s.include?(child)
sub_#{composite_name}s << child
child.parent_#{composite_name} = self
end
def delete_sub_#{composite_name}(child)
return unless sub_#{composite_name}s.include?(child)
sub_#{composite_name}s.delete(child)
child.parent_#{composite_name} = nil
end
}
class_eval(code)
end
end
class Tiger < CompositeBase
def parent_population
end
memeber_of :population
memeber_of :classification
end
class Tree < CompositeBase
memeber_of :population
memeber_of :classification
end
class Jungle < CompositeBase
composite_of :population
end
class Species < CompositeBase
composite_of :classification
end
tiger = Tiger.new('tony')
jungle = Jungle.new('jungle tigers')
jungle.add_sub_population(tiger)
p tiger.parent_population
=begin
#<Jungle:0x007faef18d0f48 @name="jungle tigers", @sub_populations=[#<Tiger:0x007faef18d0f98 @name="tony", @parent_population=#<Jungle:0x007faef18d0f48 ...>>]>
=end
|
# Instance variables begin with @
# Class variables begin with @@
class Monster
@@num_of_monsters = 0
# Use "end" to conclude method, similar to {}
def initialize(id, name, place)
@monster_id = id
@monster_name = name
@monster_place = place
end
# Use # to concatenate variables with strings
def display_details()
puts "Monster id #@monster_id"
puts "Monster name #@monster_name"
puts "Monster address #@monster_place"
end
def total_num_of_monsters()
@@num_of_monsters += 1
puts "Total number of monsters: #@@num_of_monsters"
puts ""
end
end
# Create Objects
monster1 = Monster.new("1", "Mothra", "Paris, France")
monster2 = Monster.new("2", "Godzilla", "Madrid, Spain")
# Array with different types of objects
array = ["Mothra", 10, 3.14, "Godzilla", 5, 2.67]
# For loop using | |
puts "***** FOR LOOP ******"
array.each do |i|
puts i
end
puts "*********************"
# Call Methods
monster1.display_details()
monster1.total_num_of_monsters()
monster2.display_details()
monster2.total_num_of_monsters()
|
class Song < ApplicationRecord
validates :artist, presence: true
validates :name, presence: true
end
|
class Backer
def initialize(name)
@name = name
end
attr_accessor :name
def back_project(project)
ProjectBacker.new(project,self)
end
def backed_projects
pair_list = ProjectBacker.all.select {|projback| projback.backer == self }
pair_list.map {|pair| pair.project}
end
end |
# Redmine - project management software
# Copyright (C) 2006-2011 Jean-Philippe Lang
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
require File.expand_path('../../test_helper', __FILE__)
class AuthSourcesControllerTest < ActionController::TestCase
fixtures :users
def setup
@request.session[:user_id] = 1
end
def test_index
get :index
assert_response :success
assert_template 'index'
assert_not_nil assigns(:auth_sources)
end
def test_new
get :new
assert_response :success
assert_template 'new'
assert_kind_of AuthSource, assigns(:auth_source)
assert assigns(:auth_source).new_record?
end
def test_create
assert_difference 'AuthSource.count' do
post :create, :auth_source => {:name => 'Test'}
end
assert_redirected_to '/auth_sources'
auth_source = AuthSource.first(:order => 'id DESC')
assert_equal 'Test', auth_source.name
end
def test_edit
auth_source = AuthSource.generate!(:name => 'TestEdit')
get :edit, :id => auth_source.id
assert_response :success
assert_template 'edit'
assert_equal auth_source, assigns(:auth_source)
end
def test_update
auth_source = AuthSource.generate!(:name => 'TestEdit')
post :update, :id => auth_source.id, :auth_source => {:name => 'TestUpdate'}
assert_redirected_to '/auth_sources'
assert_equal 'TestUpdate', auth_source.reload.name
end
def test_destroy_without_users
auth_source = AuthSource.generate!(:name => 'TestEdit')
assert_difference 'AuthSource.count', -1 do
post :destroy, :id => auth_source.id
end
assert_redirected_to '/auth_sources'
end
def test_destroy_with_users
auth_source = AuthSource.generate!(:name => 'TestEdit')
User.generate!(:auth_source => auth_source)
assert_no_difference 'AuthSource.count' do
post :destroy, :id => auth_source.id
end
assert_redirected_to '/auth_sources'
assert AuthSource.find(auth_source.id)
end
end
|
class OpenJtalk
VERSION = "0.8.0"
HTS_VERSION = "1.09"
OPEN_JTALK_VERSION = "1.08"
end
|
# frozen_string_literal: true
require 'rails_helper'
RSpec.describe Adapter::Adapters::Cast do
describe '.new' do
subject(:subject_class) { described_class.new(value) }
context 'when params is valid' do
let(:value) { { query: 'query' } }
it 'response with valid array keys' do
expect(subject_class.query).to eql(value[:query])
end
end
end
describe '.call' do
subject(:subject_class) do
described_class.new(value).call
end
let(:response) { JSON(subject_class.body) }
let(:data) { JSON(subject_class.body)['data'].first }
context 'call describe class with cast type' do
let(:cast) { 'Edward Norton' }
let(:value) { { query: 819, type: :cast } }
it 'response with valid status' do
VCR.use_cassette(cast, record: :once) do
expect(subject_class.status).to eql(200)
end
end
it 'response with valid cast infos' do
VCR.use_cassette(cast, record: :once) do
expect(data.keys).to match_array(%w[id name profilePath gender movies])
expect(data['name']).to eql(cast)
end
end
end
context 'call describe class with inexisten cast' do
let(:value) { { query: -1, type: :cast } }
let(:cast) { 'Not existent cast' }
it 'response with valid status' do
VCR.use_cassette(cast, record: :once) do
expect(subject_class.status).to eql(200)
end
end
it 'response with valid movie infos' do
VCR.use_cassette(cast, record: :once) do
expect(data).to be_nil
end
end
end
context 'call describe class with 500 error' do
let(:value) { { query: -1 } }
let(:cast) { '500_cast' }
it 'response with valid status' do
VCR.use_cassette(cast, record: :once) do
expect(subject_class.status).to eql(500)
end
end
end
end
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.