text stringlengths 10 2.61M |
|---|
class User < ApplicationRecord
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable, :trackable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :validatable#, :confirmable
attr_accessor :current_password
# 8~32文字内で半角英数字が1つ以上含まれている
VALID_PASSWORD_REGEX = /\A(?=.*?[a-z])(?=.*?\d)[a-z\d]{8,32}+\z/i
#松田変更ここから
# validates :password, format: { with: VALID_PASSWORD_REGEX }
validates :password, format: { with: VALID_PASSWORD_REGEX }, on: :update, allow_blank: true
#松田変更ここまで
VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i
validates :email, format: { with: VALID_EMAIL_REGEX }
validates :user_name, presence: true, uniqueness: true
mount_uploader :image, ImageUploader
def update_without_current_password(params, *options)
# edit機能を使うためにユーザーのパスワードを入力するというdeviseの使用を変更するため
params.delete(:current_password)
# パスワード、確認パスワードが両方入力されているときのみ更新できるようにするため
if params[:password].blank? && params[:password_confirmation].blank?
params.delete(:password)
params.delete(:password_confirmation)
end
result = update_attributes(params, *options)
clean_up_passwords
result
end
end
|
require 'json'
class ListsController < ApplicationController
def index
@public_lists = policy_scope(List.where(public: true))
authorize @public_lists
end
def show
@list = List.friendly.find(params[:id])
end
def new
@list = List.new
authorize @list
end
def create
@list = List.new
@list.assign_attributes(list_params)
@list.user = current_user
authorize @list
if @list.save
flash[:notice] = "Wishlist was saved successfully."
redirect_to @list
else
flash.now[:alert] = "Error creating wishlist. Please try again."
render :new
end
end
def edit
@list = List.friendly.find(params[:id])
authorize @list
end
def update
@list = List.friendly.find(params[:id])
@list.assign_attributes(list_params)
authorize @list
if @list.save
flash[:notice] = "Wishlist was updated successfully."
redirect_to @list
else
flash.now[:alert] = "Error saving wishlist. Please try again."
render :edit
end
end
def destroy
@list = List.friendly.find(params[:id])
authorize @list
if @list.destroy
flash[:notice] = "\"#{@list.name}\" was deleted successfully."
redirect_to action: :index
else
flash.now[:alert] = "There was an error deleting the wishlist."
render :show
end
end
private
def list_params
params.require(:list).permit(:name, :description, :public)
end
end
|
class Question < ApplicationRecord
has_many :responses
belongs_to :user
belongs_to :topic, class_name: "Auth::Topic"
attachment :project_files
include Commentable
def has_topic(topic)
topic.each do |t|
if t == topic
return true
end
end
return false
end
end
|
require 'rails_helper'
RSpec.describe 'User updates Protocol in SPARC', type: :request, enqueue: false do
describe 'full lifecycle' do
it 'should update the Protocol', sparc_api: :get_protocol_1 do
protocol = create(:protocol, sparc_id: 1, sponsor_name: "Original sponsor name")
user_updates_protocol_in_sparc
expect(protocol.reload.sponsor_name).to eq("GILEAD")
end
end
private
def user_updates_protocol_in_sparc
notification = build(:notification_protocol_update, sparc_id: 1)
params = {
notification: {
sparc_id: notification.sparc_id,
kind: notification.kind,
action: notification.action,
callback_url: "http://localhost:5000/v1/protocols/1.json"
}
}
sparc_sends_notification_post params
end
end
|
class MealType < ActiveRecord::Base
acts_as_content_block({:versioned => false})
attr_accessible :name, :from, :to, :is_active, :from_display, :to_display, :first_slot, :second_slot, :third_slot
attr_accessor :skip_callbacks
validates :name, :from, :to, :from_display, :to_display, presence: true
validates :name, uniqueness: true
validates :first_slot, :second_slot, :third_slot, length: {
minimum: 1,
too_short: "Please add delivery slot"
}
before_save :reset_name, :if => Proc.new {|mt| ['Breakfast', 'Lunch', 'Dinner', 'All Time'].include?(mt.name_was) }
scope :active_meal_type, lambda{ where(:is_active => true) }
def reset_name
self.name = self.name_was
end
end
|
# -*- encoding: utf-8 -*-
$:.push File.expand_path("../lib", __FILE__)
require "blinky_billd/version"
Gem::Specification.new do |s|
s.name = "blinky_billd"
s.version = BlinkyBilld::VERSION
s.authors = ["James Ottaway"]
s.email = ["james@ottaway.mp"]
s.homepage = ""
s.summary = %q{Blinky + Billd}
s.description = %q{Blinky is great for controlling a build light, and Billd can tell you how healthy your builds are.
Wouldn't it be nice if they placed nicely together? Well now they do!}
s.rubyforge_project = "blinky_billd"
s.files = `git ls-files`.split("\n")
s.test_files = `git ls-files -- {test,spec,features}/*`.split("\n")
s.executables = `git ls-files -- bin/*`.split("\n").map{ |f| File.basename(f) }
s.require_paths = ["lib"]
# specify any dependencies here; for example:
# s.add_development_dependency "rspec"
# s.add_runtime_dependency "rest-client"
s.add_runtime_dependency 'blinky'
s.add_runtime_dependency 'billd'
s.add_development_dependency 'rake'
s.add_development_dependency 'rspec'
end
|
class Owner < ApplicationRecord
has_and_belongs_to_many :clubs
has_many :players, -> {distinct}, through: :clubs
end
|
# DO NOT CHANGE ANYTHING IN THIS FILE!
require "test/unit"
require_relative "./romanconvertor"
class TestRomanConvertor < Test::Unit::TestCase
@@randomValues = {
15 => "XV",
6 => "VI",
78 => "LXXVIII",
103 => "CIII"
}
@@specialValues = {
1 => "I",
5 => "V",
10 => "X",
50 => "L",
100 => "C",
500 => "D",
1000 => "M"
}
def test_toRoman_repeatingSingleDigit
assert_equal("I", toRoman(1))
assert_equal("III", toRoman(3))
end
def test_toRoman_randomSuccessfulValues
@@randomValues.each{ |key, value| assert_equal(value, toRoman(key)) }
end
def test_fromRoman_randomSuccessfulValues
@@randomValues.each{ |key, value| assert_equal(key, fromRoman(value)) }
end
def test_toRoman_specialValues
@@specialValues.each{ |key, value| assert_equal(value, toRoman(key)) }
end
def test_fromRoman_specialValues
@@specialValues.each{ |key, value| assert_equal(key, fromRoman(value)) }
end
def test_sanity
original = "MCDXCVIII"
convertedArabic = fromRoman(original)
convertedRoman = toRoman(convertedArabic)
assert_equal(original, convertedRoman)
end
def test_negativeNumber
assert_raise RangeError do
toRoman(-1)
end
end
def test_number0
assert_raise RangeError do
toRoman(0)
end
end
def test_number4000
assert_raise RangeError do
toRoman(4000)
end
end
def test_numberMoreThan4000
assert_raise RangeError do
toRoman(4001)
end
end
def test_fromRomanInvalidChars
assert_raise TypeError do
fromRoman("hwiureh")
end
end
def test_fromRomanValidButLowerCase
assert_raise TypeError do
fromRoman("ii")
end
end
end
|
require_relative 'book'
module Contacts
class Manager
def initialize(book)
@book = book
end
def run
list
@running = true
prompt while @running
end
private
def list
puts "\n== Book =="
@book.list
end
def prompt
print "\n(L)ist, (D)etails, (F)ind, (A)dd, (O)pen, (S)ave, (Q)uit? "
case gets.upcase.strip
when "L"
list
when "D"
details
when "F"
find
when "A"
add
when "O"
open
when "S"
save
when "Q"
quit
else
puts "I'm sorry, I cannot do that."
end
end
def details
number = prompt_i "Number?"
puts "\n== Contact =="
@book.details(number - 1)
end
def find
query = prompt_s "Query?"
results = @book.search(/#{query.downcase}/)
if results.count > 0
puts "\n== Matches =="
results.list
else
puts "No matches."
end
end
def add
name = prompt_s "Name?"
mobile = prompt_s "Mobile?"
@book.add Contact.new(name, mobile)
puts "Contact #{name} added."
end
def open
filename = prompt_s "Filename?"
@book.load(filename)
puts "Opened #{filename}"
end
def save
filename = prompt_s "Filename?"
@book.save(filename)
puts "Saved #{filename}"
end
def quit
puts "Bye!"
@running = false
end
def prompt_s(prompt)
print "#{prompt} "
gets.strip
end
def prompt_i(prompt)
prompt_s(prompt).to_i
end
end
end
|
class StatusManager < ApplicationRecord
belongs_to :course, optional: true
belongs_to :project, optional: true
belongs_to :user, optional: true
belongs_to :article, optional: true
belongs_to :status, optional: true
end
|
RSpec.configure do |config|
config.include FactoryGirl::Syntax::Methods
# See lib/tasks/factory_girl.rake for FactoryGirl.lint task
end
|
#encoding: utf-8
module ActiveAdmin::ViewHelpers
def link_to_add_fields(name, f, association)
new_object = f.object.class.reflect_on_association(association).klass.new
fields = f.fields_for(association, new_object, :child_index => "new_#{association}") do |builder|
render("update_#{association.to_s}", :item => builder)
end
link_to_function(name, ("add_fields(this, \"#{association}\", \"#{escape_javascript(fields)}\")"))
end
def return_url(imageable_type, imageable_id)
"admin/photos/edit_images?imageable_type=#{imageable_type}&imageable_id=#{imageable_id}"
end
def photo_type(value)
type = [ "正常", "标志", "封面"]
type[value.to_i]
end
end
|
module Elements
class EssenceResource < Essence
belongs_to :value, :class_name => '::Resource'
def serializable_hash(options=nil)
if value.present?
hash = value.serializable_hash
hash['href'] = value.url
hash['html'] = "#{value.title} (#{value.file_name})"
hash
else
nil
end
end
end
end
|
class Crime < ApplicationRecord
has_many_attached :images
has_many_attached :files
has_one_attached :clip
has_many :messages
validate :check_past_date
def check_past_date
errors.add(:fecha, "debe ser en el pasado") unless fecha < DateTime.now
end
end
|
# -*- encoding : utf-8 -*-
require 'rails_helper'
RSpec.describe Comment, type: :model do
it 'has a valid factory' do
expect(create(:comment)).to be_valid
end
end
|
module CamaleonCms
module Metas
extend ActiveSupport::Concern
included do
# options and metas auto save support
attr_accessor :data_options
attr_accessor :data_metas
after_create :save_metas_options, unless: :save_metas_options_skip
before_update :fix_save_metas_options_no_changed
end
# Add meta with value or Update meta with key: key
# return true or false
def set_meta(key, value)
metas.where(key: key).update_or_create({ value: fix_meta_value(value) })
cama_set_cache("meta_#{key}", value)
end
# return value of meta with key: key,
# if meta not exist, return default
# return default if meta value == ""
def get_meta(key, default = nil)
key_str = key.is_a?(Symbol) ? key.to_s : key
cama_fetch_cache("meta_#{key_str}") do
option = metas.loaded? ? metas.select { |m| m.key == key }.first : metas.where(key: key_str).first
res = ''
if option.present?
value = begin
JSON.parse(option.value)
rescue StandardError
option.value
end
res = begin
(value.is_a?(Hash) ? value.with_indifferent_access : value)
rescue StandardError
option.value
end
end
res == '' ? default : res
end
end
# delete meta
def delete_meta(key)
metas.where(key: key).destroy_all
cama_remove_cache("meta_#{key}")
end
# return configurations for current object, sample: {"type":"post_type","object_id":"127"}
def options(meta_key = '_default')
get_meta(meta_key, {})
end
alias cama_options options
# add configuration for current object
# key: attribute name
# value: attribute value
# meta_key: (String) name of the meta attribute
# sample: mymodel.set_custom_option("my_settings", "color", "red")
def set_option(key, value = nil, meta_key = '_default')
return if key.nil?
data = cama_options(meta_key)
data[key] = fix_meta_var(value)
set_meta(meta_key, data)
value
end
# return configuration for current object
# key: attribute name
# default: if attribute not exist, return default
# return default if option value == ""
# return value for attribute
def get_option(key = nil, default = nil, meta_key = '_default')
values = cama_options(meta_key)
key = key.to_sym
values.key?(key) && values[key] != '' ? values[key] : default
end
# delete attribute from configuration
def delete_option(key, meta_key = '_default')
values = cama_options(meta_key)
key = key.to_sym
values.delete(key) if values.key?(key)
set_meta(meta_key, values)
end
# set multiple configurations
# h: {ket1: "sdsds", ff: "fdfdfdfd"}
def set_options(h = {}, meta_key = '_default')
return unless h.present?
data = cama_options(meta_key)
PluginRoutes.fixActionParameter(h).to_sym.each do |key, value|
data[key] = fix_meta_var(value)
end
set_meta(meta_key, data)
end
alias set_multiple_options set_options
# save multiple metas
# sample: set_metas({name: 'Owen', email: 'owenperedo@gmail.com'})
def set_metas(data_metas)
(data_metas.nil? ? {} : data_metas).each do |key, value|
set_meta(key, value)
end
end
# permit to skip save_metas_options in specific models
def save_metas_options_skip
false
end
# fix to save options and metas when a model was not changed
def fix_save_metas_options_no_changed
save_metas_options # unless self.changed?
end
# save all settings for this post type received in data_options and data_metas attribute (options and metas)
# sample: Site.first.post_types.create({name: "owen", slug: "my_post_type", data_options: { has_category: true, default_layout: "my_layout" }})
def save_metas_options
set_multiple_options(data_options)
return unless data_metas.present?
data_metas.each do |key, val|
set_meta(key, val)
end
end
private
# fix to parse value
def fix_meta_value(value)
value = value.to_json if value.is_a?(Array) || value.is_a?(Hash) || value.is_a?(ActionController::Parameters)
fix_meta_var(value)
end
# fix to detect type of the variable
def fix_meta_var(value)
value = value.to_var if value.is_a?(String)
value
end
end
end
|
class User < ApplicationRecord
has_one :author
has_many :reviews
has_many :books, through: :reviews
has_secure_password
validates :agreement, acceptance: {on: :create}
validates :email, confirmation: true
end
|
class User < ActiveRecord::Base
validates :username, uniqueness: true
validates :username, :password, presence: true
def token
Digest::MD5.new.update(self.username + '%' + self.password).to_s
end
end
|
# You can have Landlord route to the appropriate Tenant by adding some Rack middleware.
# Landlord can support many different "Elevators" that can take care of this routing to your data.
# Require whichever Elevator you're using below or none if you have a custom one.
#
# require 'landlord/elevators/generic'
# require 'landlord/elevators/domain'
require 'landlord/elevators/subdomain'
#
# Landlord Configuration
#
Landlord.configure do |config|
# In order to migrate all of your Tenants you need to provide a list of Tenant names to Landlord.
# You can make this dynamic by providing a Proc object to be called on migrations.
# This object should yield an array of strings representing each Tenant name.
#
# config.tenant_names = lambda{ Customer.pluck(:tenant_name) }
# config.tenant_names = ['tenant1', 'tenant2']
#
config.tenant_names = lambda { ToDo_Tenant_Or_User_Model.pluck :database }
# There are cases where you might want some schemas to always be in your search_path
# e.g when using a PostgreSQL extension like hstore.
# Any schemas added here will be available along with your selected Tenant.
#
# config.persistent_schemas = %w{ hstore }
end
# Setup a custom Tenant switching middleware. The Proc should return the name of the Tenant that
# you want to switch to.
# Rails.application.config.middleware.use 'Landlord::Elevators::Generic', lambda { |request|
# request.host.split('.').first
# }
# Rails.application.config.middleware.use 'Landlord::Elevators::Domain'
Rails.application.config.middleware.use 'Landlord::Elevators::Subdomain'
|
require 'submarine'
describe Submarine do
let(:sub){Submarine.new 'A2', :north}
let(:sub_north){Submarine.new 'B2', :north}
let(:sub_east){Submarine.new 'B2', :east}
let(:sub_south){Submarine.new 'B2', :south}
let(:sub_west){Submarine.new 'B2', :west}
it 'has size 2' do
expect(sub.size).to eq 2
end
it 'knows all positions when facing north' do
expect(sub_north.position).to eq ['B2','B1']
end
it 'knows all positions when facing east' do
expect(sub_east.position).to eq ['B2','C2']
end
it 'knows all positions when facing south' do
expect(sub_south.position).to eq ['B2','B3']
end
it 'knows all positions when facing west' do
expect(sub_west.position).to eq ['B2','A2']
end
it 'gets hit in any of the positions it is in' do
expect(sub_north.hit 'B2').to eq :hit
expect(sub_north.hit 'B1').to eq :hit
end
it 'should handle collisions on start position' do
expect(sub.collided? sub).to be true
end
it 'should handle collisions on location other than start position' do
expect(sub.collided? sub_west).to be true
end
it 'should not be able to be hit more than once in the same place' do
sub_north.hit 'B2'
expect(sub_north.hits).to eq ['B2']
sub_north.hit 'B2'
expect(sub_north.hits).to eq ['B2']
end
end |
class Item < ActiveRecord::Base
attr_accessible :name, :price, :sub_category_id
has_many :photos
has_many :reservations
belongs_to :sub_category
def primary_photo
self.photos.first
end
class << self
def new_arrivals
Item.where("created_at > ?", 3.days.ago).order("CREATED_AT DESC").limit(3)
end
def popular_picks
Item.where("created_at < ?", 3.days.ago).limit(12).order("RANDOM()")
end
end
end
|
class Site < ActiveRecord::Base
# has_many :site_inventories
has_many :items
has_many :line_items
has_many :invoices, through: :line_items
default_scope {where(:deleted => nil)}
end
|
class Cat < ApplicationRecord
COLORS = [
"red",
"blue",
"yellow",
"green",
"purple"
].freeze
validates :birth_date, :name, :description, presence: true
validates :sex, presence: true, inclusion: { in: %w(M F) }
validates :color, presence: true, inclusion: COLORS
def age
Date.today.year - birth_date.year
end
has_many :cat_rental_requests,
primary_key: :id,
foreign_key: :cat_id,
class_name: :CatRentalRequest,
dependent: :destroy
end
|
# frozen_string_literal: false
module AsciiPngfy
module Settings
# Reponsibilities
# - Keeps track of the text and replacement_text setting
# - Replaces unsupported text characters with replacement text
# - Validates text and replacement_text
# rubocop: disable Metrics/ClassLength
class TextSetting
include SetableGetable
def initialize(settings)
self.settings = settings
self.text = ''
set('<3 Ascii-Pngfy <3')
end
def get
text.dup
end
# The philosophy behind this method is as follows:
# - The desired_text cannot be empty pre replacement. If it is an error is raised
#
# - When no replacement text is passed, the desired_text is considered as is by
# skipping the replacement procedure
#
# - When a replacement text is passed though, the replacement text is validated and
# all unsupported text characters are replaced with the replacement text
#
# - The text is then validated post replacement to make sure it is not empty,
# the same as pre replacement
#
# - At this point the text is validated to only contain supported ASCII characters
# and has its dimensions checked in terms of the needed png texture size to fit
# the resulting text along with the character spacing previously set.
#
# - Finally the text setting is updated to the resulting, optionally replaced text
def set(desired_text, desired_replacement_text = nil)
pre_replacement_text_validation(desired_text, desired_replacement_text)
if replacement_desired?(desired_replacement_text)
desired_replacement_text = validate_replacement_text(desired_replacement_text)
desired_text = replace_unsupported_characters(from: desired_text, with: desired_replacement_text)
end
post_replacement_text_validation(desired_text)
validate_text_contents(desired_text)
validate_text_image_dimensions(desired_text)
# set the text to a duplicate of the original text to avoid string injection
self.text = desired_text.dup
desired_text
end
def initialize_copy(original_text_setting)
self.text = original_text_setting.text.dup
end
protected
attr_accessor(:text)
private
attr_accessor(:settings)
def character_supported?(some_character)
SUPPORTED_ASCII_CHARACTERS.include?(some_character)
end
def extract_unsupported_characters(some_string)
unsupported_characters = []
some_string.each_char do |some_char|
unsupported_characters << some_char unless character_supported?(some_char)
end
unsupported_characters
end
def string_supported?(some_string)
# also returns true when the string is empty, so an undesired empty string must
# be handled separately
extract_unsupported_characters(some_string).empty?
end
def validate_replacement_text(some_text)
return some_text if string_supported?(some_text)
error_message = "#{some_text.inspect} is not a valid replacement string. "\
"Must contain only characters with ASCII code #{SUPPORTED_ASCII_CODES.min} "\
"or in the range (#{SUPPORTED_ASCII_CODES_WITHOUT_NEWLINE_RANGE})."
raise AsciiPngfy::Exceptions::InvalidReplacementTextError, error_message
end
def replace_unsupported_characters(from:, with:)
text_with_replacements = ''
from.each_char do |text_character|
replacement_text = character_supported?(text_character) ? text_character : with
text_with_replacements << replacement_text
end
text_with_replacements
end
def replacement_desired?(replacement_text)
!!replacement_text
end
def pre_replacement_text_validation(desired_text, desired_replacement_text)
return desired_text unless desired_text.empty?
error_message = 'Text cannot be empty because that would result in a PNG with a width or height of zero. '\
"Must contain at least one character with ASCII code #{SUPPORTED_ASCII_CODES.min} "\
"or in the range (#{SUPPORTED_ASCII_CODES_WITHOUT_NEWLINE_RANGE})."
# hint the user that the desired replacement text is also empty
if replacement_desired?(desired_replacement_text) && desired_replacement_text.empty?
error_message << ' Hint: Both the text and the replacement text are empty.'
end
raise AsciiPngfy::Exceptions::EmptyTextError, error_message
end
def post_replacement_text_validation(desired_text)
return desired_text unless desired_text.empty?
error_message = 'Text cannot be empty because that would result in a PNG with a width or height of zero. '\
"Must contain at least one character with ASCII code #{SUPPORTED_ASCII_CODES.min} "\
"or in the range (#{SUPPORTED_ASCII_CODES_WITHOUT_NEWLINE_RANGE}). "\
'Hint: An empty replacement text causes text with only unsupported characters to end up as '\
'empty string.'
raise AsciiPngfy::Exceptions::EmptyTextError, error_message
end
def validate_text_contents(some_text)
# this method only accounts for non-empty strings that contains unsupported characters
# empty strings are handled separately to separate different types of errors more clearly
return some_text if string_supported?(some_text)
un_supported_characters = extract_unsupported_characters(some_text)
un_supported_inspected_characters = un_supported_characters.map(&:inspect)
un_supported_characters_list = "#{un_supported_inspected_characters[0..-2].join(', ')} and "\
"#{un_supported_inspected_characters.last}"
error_message = "#{un_supported_characters_list} are all invalid text characters. "\
"Must contain only characters with ASCII code #{SUPPORTED_ASCII_CODES.min} "\
"or in the range (#{SUPPORTED_ASCII_CODES_WITHOUT_NEWLINE_RANGE})."
raise AsciiPngfy::Exceptions::InvalidCharacterError, error_message
end
def validate_text_image_width(desired_text, image_width)
return desired_text unless image_width > AsciiPngfy::MAX_RESULT_PNG_IMAGE_WIDTH
longest_text_line = RenderingRules.longest_text_line(desired_text)
capped_text = cap_string(longest_text_line, '..', 60)
error_message = "The text line #{capped_text.inspect} is too long to be represented in a "\
"#{AsciiPngfy::MAX_RESULT_PNG_IMAGE_WIDTH} pixel wide png. Hint: Use shorter "\
'text lines and/or reduce the horizontal character spacing.'
raise AsciiPngfy::Exceptions::TextLineTooLongError, error_message
end
def validate_text_image_height(desired_text, image_height)
return desired_text unless image_height > AsciiPngfy::MAX_RESULT_PNG_IMAGE_HEIGHT
capped_text = cap_string(desired_text, '..', 60)
error_message = "The text #{capped_text.inspect} contains too many lines to be represented in a "\
"#{MAX_RESULT_PNG_IMAGE_HEIGHT} pixel high png. Hint: Use less text lines and/or "\
'reduce the vertical character spacing.'
raise AsciiPngfy::Exceptions::TooManyTextLinesError, error_message
end
def validate_text_image_dimensions(desired_text)
image_width = AsciiPngfy::RenderingRules.png_width(settings, desired_text)
image_height = AsciiPngfy::RenderingRules.png_height(settings, desired_text)
validate_text_image_width(desired_text, image_width)
validate_text_image_height(desired_text, image_height)
end
def cap_string(some_string, desired_separator, desired_cap_length)
if some_string.length <= desired_cap_length
some_string
else
half_cap_length = (desired_cap_length - desired_separator.length) / 2
string_beginning_portion = some_string[0, half_cap_length]
string_end_portion = some_string[-half_cap_length..]
"#{string_beginning_portion}#{desired_separator}#{string_end_portion}"
end
end
end
end
# rubocop: enable Metrics/ClassLength
end
|
class AddAasmStateToSharedLists < ActiveRecord::Migration[6.0]
def change
add_column :shared_lists, :aasm_state, :string
end
end
|
require_relative "modules"
module Lib
class Book
include Jsonable
attr_reader :title, :author, :times_taken, :id
def initialize(title, author, id)
raise TypeError, 'Title must be a strings' unless title.is_a?(String)
raise TypeError, 'Author must be an author' unless author.is_a?(Author)
@title = title
@author = author
@times_taken = 0
@id = id || self.object_id
end
def to_s
"'#{@title}' by #{@author.name}"
end
def take
@times_taken += 1
end
end
end |
require "nokogiri"
def parse_xml(xml_file)
array = Array.new
hash = Hash.new
doc = Nokogiri::XML(open(xml_file).read)
doc.search("note").map do |note|
array.push(note.name.downcase)
end
new_hash = doc.root.element_children.each_with_object(Hash.new) do |element, hash|
hash[element.name.to_sym] = element.content
end
hash[array.join] = new_hash
return hash
end
p parse_xml(Pathname.new("notes.xml")) |
require 'spec_helper'
describe BackpackTF::Price::Response do
let(:response) do
{
'raw_usd_value' => 'raw_usd_value',
'usd_currency' => 'usd_currency',
'usd_currency_index' => 'usd_currency_index'
}
end
context 'reader methods' do
before(:each) do
described_class.response = response
end
after(:each) do
described_class.response = nil
end
describe '::raw_usd_value' do
it 'returns the value' do
expect(described_class.raw_usd_value).to eq 'raw_usd_value'
end
end
describe '::usd_currency' do
it 'returns the value' do
expect(described_class.usd_currency).to eq 'usd_currency'
end
end
describe '::usd_currency_index' do
it 'returns the value' do
expect(described_class.usd_currency_index).to eq 'usd_currency_index'
end
end
describe '::items' do
after :each do
described_class.class_eval { @items = nil }
end
context 'when @items is not nil' do
before :each do
described_class.class_eval { @items = { foo: 'bar' } }
end
it 'returns @items' do
expected = described_class.class_eval { @items }
expect(described_class.items).to eq expected
end
end
context 'when @items is nil' do
before :each do
described_class.class_eval { @items = nil }
end
it 'calls .generate_items' do
expect(described_class).to receive(:generate_items)
described_class.items
end
end
end
end
describe '::generate_items' do
let(:json_response) do
fixture = file_fixture('prices.json')
JSON.parse(fixture)['response']
end
context 'using keys to generate BackpackTF::Item objects' do
before(:each) do
described_class.response = json_response
end
after(:each) do
described_class.response = nil
end
it 'each value of hash is a BackpackTF::Price::Item object' do
actual = described_class.generate_items.values
expect(actual).to all be_a BackpackTF::Price::Item
end
it 'if an item does not have a valid `defindex`, then it is ignored' do
generated_items = described_class.generate_items
expect(generated_items['Random Craft Hat']).to be_nil
end
end
end
end
|
require 'date'
require 'redcarpet'
require 'json'
require 'nokogiri'
require 'aws-sdk-s3'
require 'dimensions'
require 'safe_yaml'
require 'soffes/blog/markdown_renderer'
require 'soffes/blog/redis'
require 'soffes/blog/posts_controller'
module Soffes
module Blog
class Importer
BLOG_GIT_URL = 'https://github.com/soffes/blog.git'.freeze
MARKDOWN_OPTIONS = options = {
no_intra_emphasis: true,
tables: true,
fenced_code_blocks: true,
autolink: true,
strikethrough: true,
space_after_headers: true,
superscript: true,
with_toc_data: true,
underline: true,
highlight: true
}.freeze
AWS_ACCESS_KEY_ID = ENV['AWS_ACCESS_KEY_ID']
AWS_SECRET_ACCESS_KEY = ENV['AWS_SECRET_ACCESS_KEY']
AWS_S3_REGION = ENV['AWS_S3_REGION'] || 'us-east-1'
def initialize(local_posts_path: 'tmp/repo', update_posts: true, bucket_name: ENV['AWS_S3_BUCKET_NAME'])
@local_posts_path = local_posts_path
@update_posts = update_posts
@bucket_name = bucket_name
end
def import
if @update_posts
if !File.exists?(@local_posts_path)
puts 'Cloning posts...'
`git clone --depth 1 #{BLOG_GIT_URL} #{@local_posts_path}`
else
puts 'Updating posts...'
`cd #{@local_posts_path} && git pull origin master`
end
else
raise 'Posts not found.' unless File.exists?(@local_posts_path)
end
markdown = Redcarpet::Markdown.new(Soffes::Blog::MarkdownRenderer, MARKDOWN_OPTIONS)
count = 0
# Posts
Dir["#{@local_posts_path}/published/*"].each do |path|
matches = path.match(/\/(\d{4})-(\d{2})-(\d{2})-([\w\-]+)$/)
key = matches[4]
puts "Importing #{key}"
# Load content
contents = File.open("#{path}/#{key}.markdown").read
# Meta data
meta = {
'key' => key,
'title' => key.capitalize,
'published_at' => Date.new(matches[1].to_i, matches[2].to_i, matches[3].to_i).to_time.utc.to_i
}
# Extract YAML front matter
if result = contents.match(/\A(---\s*\n.*?\n?)^(---\s*$\n?)/m)
contents = contents[(result[0].length)...(contents.length)]
meta.merge!(YAML.safe_load(result[0]))
end
# Upload cover image
if cover_image = meta['cover_image']
local_path = "#{path}/#{cover_image}"
meta['cover_image'] = upload(local_path, "#{key}/#{cover_image}")
dimensions = Dimensions.dimensions local_path
meta['cover_image_width'] = dimensions.first
meta['cover_image_height'] = dimensions.last
end
# Parse Markdown
html = markdown.render(contents)
# Remove H1
doc = Nokogiri::HTML.fragment(html)
h1 = doc.search('.//h1').remove
meta['title'] = h1.text if h1.text.length > 0
# Upload images
doc.css('img').each do |i|
src = i['src']
next if src.start_with?('http')
image_path = "#{path}/#{src}"
next unless File.exists?(image_path)
i['src'] = upload(image_path, "#{key}/#{src}")
end
# Add HTML
meta['html'] = doc.to_html
# Add naïve word count
meta['word_count'] = doc.text.split(/\s+/m).length
# Add excerpt
meta['excerpt_html'] = doc.css('p:first-child').text
# Persist!
PostsController.insert_post(meta)
count += 1
end
puts 'Done!'
count
end
private
def redis
Soffes::Blog.redis
end
def aws
@aws ||= Aws::S3::Client.new(
region: AWS_S3_REGION,
access_key_id: AWS_ACCESS_KEY_ID,
secret_access_key: AWS_SECRET_ACCESS_KEY
)
end
def upload(local, key)
unless redis.sismember('uploaded', key)
puts " Uploading #{key}"
bucket = Aws::S3::Resource.new(client: aws).bucket(@bucket_name)
bucket.object(key).upload_file(local, acl: 'public-read')
redis.sadd('uploaded', key)
end
"https://#{@bucket_name}.s3.amazonaws.com/#{key}"
end
end
end
end
|
class Mechanic
attr_reader :name, :specialty
@@all = []
def initialize(name, specialty)
@name = name
@specialty = specialty
@@all << self
end
def self.all
@@all
end
def cars_i_fix
Car.all.select {|car| car.mechanic == self}
end
def my_customers
self.cars_i_fix.map {|car| car.owner}
end
def my_customers_names
self.my_customers.map {|customer| customer.name}
end
end
|
require 'csv'
class Employee
attr_reader :name, :email, :phone
attr_accessor :review, :salary, :satisfactory_performance, :department
def initialize(name, email, phone="", salary=nil, review = "", satisfactory_performance = true)
@name = name
@email = email
@phone = phone
@salary = salary
@review = review
@satisfactory_performance = satisfactory_performance
end
def add_review(text)
self.review = text
self.satisfactory_performance = false if has_negative_review?
end
def satisfactory_performer?
self.satisfactory_performance
end
def give_raise(percentage)
self.salary += percentage * self.salary
end
def positive_looking_review?
self.review.match(/(is|been|an).*(?<!not)\s(a|an).*\sasset/)||self.review.match(/(has|is|'s)\s(?!no).*(?<!no)effective/)
end
def negative_looking_review?
self.review.match(/(has|have|had|was)\s(?!no).*(?<!no)\sconcern/)||self.review.match(/not\sdo.*well/)
end
def has_negative_review?
negative_looking_review? && !positive_looking_review?
end
def ==(other)
name == other.name && email == other.email && phone == other.phone && salary == other.salary
end
def to_hash
{ name: name, email: email, phone: phone, salary: salary, review: review, satisfactory_performance: satisfactory_performance }
end
end
|
json.job do |json|
json.id @job.id
json.title @job.title
json.description @job.description
json.location @job.location
json.industry @job.industry
json.gender @job.gender
json.created_at @job.created_at
json.slug @job.slug
json.user_id @job.creator.id
json.education_attainment @job.education_attainment
json.min_exp @job.min_exp
json.max_exp @job.max_exp
json.type_of_employee @job.type_of_employee
json.level_of_expertise @job.level_of_expertise
json.requisition_number @job.requisition_number
json.preferred_courses @job.preferred_courses
json.requirements @job.requirements
json.company do |c|
c.name @job.company.name
c.avatar @job.company.avatar
c.overview @job.company.overview
c.why_join_us @job.company.why_join_us
c.benefits @job.company.benefits
c.website @job.company.website
end
json.creator do |c|
c.id @job.creator.id
c.email @job.creator.email
c.first_name @job.creator.first_name
c.last_name @job.creator.last_name
end
end |
require "rspec"
require "hanoi"
describe TowersofHanoi do
subject(:towers) {TowersofHanoi.new}
describe "#initialize" do
it "creates three stacks" do
expect(towers.stacks).to eq([[3, 2, 1], [], []])
end
end
describe "#move" do
it "can't choose an empty stack to move from" do
error_message = "can't move from an empty stack"
expect{ (towers.move([2, 0])) }.to raise_error(error_message)
end
before(:each) {towers.move([0, 1])}
it "moves the top disk" do
expect(towers.stacks).to eq([[3, 2],[1],[]])
end
it "can't move a bigger disk to a smaller disk" do
error_message = "can't move a bigger disk to a smaller disk"
expect{ (towers.move([0, 1])) }.to raise_error(error_message)
end
it "can't choose an invalid stack" do
error_message = "must choose a valid stack"
expect{ (towers.move([5, 0]))}.to raise_error(error_message)
end
end
describe "#won" do
before(:each) do
towers.move([0, 1])
towers.move([0, 2])
towers.move([1, 2])
towers.move([0, 1])
towers.move([2, 0])
towers.move([2, 1])
towers.move([0, 1])
end
it "should tell you if you completed the game" do
expect(towers.won?).to be_truthy
end
end
end
|
CheckoutController.class_eval do
include GoogleMaps
before_filter :check_delivery_distance
private
def check_delivery_distance
if params[:state] == "address" && params[:order]
get_distance
if @distance.kind_of?(Float) && @distance > Spree::Config[:delivery_distance].to_f
flash[:error] = t('out_of_range', :distance => Spree::Config[:delivery_distance])
redirect_to checkout_state_path(@order.state)
end
end
end
def get_distance
@distance = GoogleMaps::Directions.get_distance( Spree::Config[:address], get_address(params))
end
def get_address(opts={})
if opts[:order][:ship_address_attributes].has_key?(:address1)
"#{opts[:order][:ship_address_attributes][:address1]}, #{opts[:order][:ship_address_attributes][:city]}"
else
"#{opts[:order][:bill_address_attributes][:address1]}, #{opts[:order][:bill_address_attributes][:city]}"
end
end
end |
class ApplicationController < ActionController::Base
include Slimmer::Template
include Slimmer::GovukComponents
# Prevent CSRF attacks by raising an exception.
# For APIs, you may want to use :null_session instead.
protect_from_forgery with: :exception
rescue_from GdsApi::HTTPNotFound, with: :error_not_found
rescue_from GdsApi::HTTPGone, with: :gone
private
def error_not_found
render status: :not_found, plain: "404 error not found"
end
def gone
render status: :gone, plain: "410 gone"
end
end
|
# -*- mode: ruby -*-
# vi: set ft=ruby :
vagrant_dir = File.join(File.expand_path(File.dirname(__FILE__)), 'vagrant')
unless Vagrant.has_plugin?("vagrant-docker-compose")
system("vagrant plugin install vagrant-docker-compose")
puts "Dependencies installed, please try the command again."
exit
end
# @param swap_size_mb [Integer] swap size in megabytes
# @param swap_file [String] full path for swap file, default is /swapfile1
# @return [String] the script text for shell inline provisioning
def create_swap(swap_size_mb, swap_file = "/swapfile1")
<<-EOS
if [ ! -f #{swap_file} ]; then
echo "Creating #{swap_size_mb}mb swap file=#{swap_file}. This could take a while..."
dd if=/dev/zero of=#{swap_file} bs=1024 count=#{swap_size_mb * 1024}
mkswap #{swap_file}
chmod 0600 #{swap_file}
swapon #{swap_file}
if ! grep -Fxq "#{swap_file} swap swap defaults 0 0" /etc/fstab
then
echo "#{swap_file} swap swap defaults 0 0" >> /etc/fstab
fi
fi
EOS
end
Vagrant.configure("2") do |config|
# Store the current version of Vagrant for use in conditionals when dealing
# with possible backward compatible issues.
vagrant_version = Vagrant::VERSION.sub(/^v/, '')
config.vm.box = "hashicorp/boot2docker"
config.vm.define "docker-wordpress"
#boot2docker ssh
config.ssh.insert_key = true
config.ssh.username = "docker"
config.ssh.password = "tcuser"
config.ssh.guest_port = 22
config.ssh.port = 2200
config.ssh.host = '127.0.0.1'
# Configurations from 1.0.x can be placed in Vagrant 1.1.x specs like the following.
config.vm.provider :virtualbox do |v|
# Set the box name in VirtualBox to match the working directory.
v.name = "Docker-Wordpress"
end
# Local Machine Hosts
#
# If the Vagrant plugin hostsupdater (https://github.com/cogitatio/vagrant-hostsupdater) is
# installed, the following will automatically configure your local machine's hosts file to
# be aware of the domains specified below. Watch the provisioning script as you may need to
# enter a password for Vagrant to access your hosts file.
#
# By default, we'll include the domains set up by VVV through the vvv-hosts file
# located in the www/ directory.
#
# Other domains can be automatically added by including a vvv-hosts file containing
# individual domains separated by whitespace in subdirectories of www/.
if defined?(VagrantPlugins::HostsUpdater)
# Recursively fetch the paths to all vvv-hosts files under the www/ directory.
paths = Dir[File.join(vagrant_dir, 'www', '**', 'vvv-hosts')]
# Parse the found vvv-hosts files for host names.
hosts = paths.map do |path|
# Read line from file and remove line breaks
lines = File.readlines(path).map(&:chomp)
# Filter out comments starting with "#"
lines.grep(/\A[^#]/)
end.flatten.uniq # Remove duplicate entries
# Pass the found host names to the hostsupdater plugin so it can perform magic.
config.hostsupdater.aliases = hosts
config.hostsupdater.remove_on_suspend = true
end
# Private Network (default)
#
# A private network is created by default. This is the IP address through which your
# host machine will communicate to the guest. In this default configuration, the virtual
# machine will have an IP address of 192.168.50.4 and a virtual network adapter will be
# created on your host machine with the IP of 192.168.50.1 as a gateway.
#
# Access to the guest machine is only available to your local host. To provide access to
# other devices, a public network should be configured or port forwarding enabled.
#
# Note: If your existing network is using the 192.168.50.x subnet, this default IP address
# should be changed. If more than one VM is running through VirtualBox, including other
# Vagrant machines, different subnets should be used for each.
#
config.vm.network :private_network, id: "vvv_primary", ip: "192.168.50.10"
config.vm.network(:forwarded_port, guest: 8080, host: 8080)
#config.vm.network(:forwarded_port, guest: 3333, host: 3333)
# /srv/www/
# /vagrant/
#
# If a www directory exists in the same directory as your Vagrantfile, a mapped directory
# inside the VM will be created that acts as the default location for nginx sites. Put all
# of your project files here that you want to access through the web server
if vagrant_version >= "1.3.0"
config.vm.synced_folder File.join(vagrant_dir, "www/"), "/srv/www/", :owner => "www-data", :mount_options => [ "dmode=775", "fmode=664" ]
config.vm.synced_folder File.expand_path(File.dirname(__FILE__)), "/vagrant/", :owner => "www-data", :mount_options => [ "dmode=775", "fmode=664" ]
else
config.vm.synced_folder File.join(vagrant_dir, "www/"), "/srv/www/", :owner => "www-data", :extra => 'dmode=775,fmode=664'
config.vm.synced_folder File.expand_path(File.dirname(__FILE__)), "/vagrant/", :owner => "www-data", :extra => 'dmode=775,fmode=664'
end
config.vm.provision "fix-no-tty", type: "shell" do |s|
s.privileged = false
s.inline = "sudo sed -i '/tty/!s/mesg n/tty -s \\&\\& mesg n/' /root/.profile"
end
# The Parallels Provider does not understand "dmode"/"fmode" in the "mount_options" as
# those are specific to Virtualbox. The folder is therefore overridden with one that
# uses corresponding Parallels mount options.
config.vm.provider :parallels do |v, override|
override.vm.synced_folder File.join(vagrant_dir, "www/"), "/srv/www/", :owner => "www-data", :mount_options => []
override.vm.synced_folder File.expand_path(File.dirname(__FILE__)), "/vagrant/", :owner => "www-data", :mount_options => []
end
# The Hyper-V Provider does not understand "dmode"/"fmode" in the "mount_options" as
# those are specific to Virtualbox. Furthermore, the normal shared folders need to be
# replaced with SMB shares. Here we switch all the shared folders to us SMB and then
# override the www folder with options that make it Hyper-V compatible.
config.vm.provider :hyperv do |v, override|
override.vm.synced_folder File.join(vagrant_dir, "www/"), "/srv/www/", :owner => "www-data", :mount_options => ["dir_mode=0775","file_mode=0774","forceuid","noperm","nobrl","mfsymlinks"]
override.vm.synced_folder File.expand_path(File.dirname(__FILE__)), "/vagrant/", :owner => "www-data", :mount_options => ["dir_mode=0775","file_mode=0664","forceuid","noperm","nobrl","mfsymlinks"]
# Change all the folder to use SMB instead of Virtual Box shares
override.vm.synced_folders.each do |id, options|
if ! options[:type]
options[:type] = "smb"
end
end
end
config.vm.provision :docker
config.vm.provision :docker_compose, yml: ["/vagrant/docker-compose.yml"], rebuild: true, project_name: "myproject", run: "always"
end
|
class AlterProjectsAddNoteIdColumn < ActiveRecord::Migration[5.0]
def change
add_column :projects, :note_id, :integer
add_index :projects, :note_id
end
end
|
module SupplyTeachers::Admin::UploadsHelper
def css_classes_for_file_upload(journey, attribute, extra_classes = [])
error = journey.errors[attribute].first
css_classes = ['govuk-file-upload'] + extra_classes
css_classes += %w[govuk-input--error govuk-input] if error.present?
css_classes
end
def warning_details(uploads)
uploads_more_than_one = uploads.count > 1
"Upload session #{uploads.map(&:datetime).to_sentence} #{uploads_more_than_one ? 'are' : 'is'} #{uploads.map { |u| t("supply_teachers.admin.uploads.index.#{u.aasm_state}") }.to_sentence.downcase}. Uploading new spreadsheets will cancel #{uploads_more_than_one ? 'those sessions' : 'that session'}."
end
end
|
# class Compliance
module Compliance
# module CodeReview Extension
module CodeReview
extend ActiveSupport::Concern
included do
def code_review
session[:prev_page] = request.env['HTTP_REFERER']
flash[:notice] = nil
@headers = @encounter.prepare_header_data
@encounter.generate_default_audit_codes if @encounter.can_copy_audit_codes
end
private
def compliance_codes
@encounter = ::Compliance::Encounter.find_by_id(params[:id])
@work_type = @encounter.worktype
allocate_code_values
allocate_supplementary_values
error_category_details
@ip_encounter = @encounter.ip?
end
def allocate_code_values
@dx_codes = @encounter.dx_codes
@px_codes = @encounter.px_codes
@discharge_disposition = @encounter.discharge_dispositions
@poo = @encounter.point_of_origins
@drg_codes = @encounter.drg_codes
end
def allocate_supplementary_values
@providers = @work_type.options_for_providers
@coders = @work_type.options_for_coders
@auditors = @work_type.options_for_auditors
end
def error_category_details
@dx_categories = Category.dx_categories
@px_categories = Category.px_categories
@drg_categories = Category.drg_categories
end
def autoselect_code_types(encounter, code_types, type)
return unless type == 'dx'
code_types = code_types.join.split(' ')
encounter.select_code_type(code_types)
end
end
end
end
|
class Game
attr_reader :player1, :player2, :turn
def self.create(player1, player2)
@game = Game.new(player1, player2)
end
def self.instance
@game
end
def initialize(player1, player2, turn = [true,false].sample)
@player1 = player1
@player2 = player2
@turn = turn
end
def attack
@turn ? player2.reduce_hp : player1.reduce_hp
end
def switch_turn
@turn == true ? @turn = false : @turn = true
end
end
|
class Subscription < ActiveRecord::Base
attr_accessible :active, :user_id, :workshop_id
# Relationships
belongs_to :workshop
belongs_to :user
end
|
class CreateVideoPreviews < ActiveRecord::Migration
def up
create_table :video_previews do |t|
t.belongs_to :previewable, polymorphic: true
t.text :stream_url
t.timestamps null: false
end
add_index :video_previews, [:previewable_id, :previewable_type]
end
def down
drop_table :video_previews
end
end
|
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe Sidekiq::Instrumental do
it 'has a version number' do
expect(described_class::VERSION).not_to be nil
end
describe '::config' do
describe '::config' do
it 'should return a Configuration object' do
expect(described_class.config)
.to be_an_instance_of(described_class::Configuration)
end
end
end
describe '::configure' do
before do
allow(described_class).to receive(:register)
end
it 'should yield to the passed block' do
expect { |b| described_class.configure(&b) }.to yield_control
end
it 'should yield the configuration object' do
expect { |b| described_class.configure(&b) }
.to yield_with_args(described_class.config)
end
end
describe '::register' do
context 'when sidekiq run as a server' do
before do
allow(Sidekiq).to receive(:server?).and_return(true)
end
it 'should register server middleware' do
server_chain = double('Sidekick::MiddlewareChain')
config = double('Chain')
allow(config).to receive(:server_middleware).and_yield(server_chain)
allow(config).to receive(:client_middleware)
allow(Sidekiq).to receive(:configure_server).and_yield(config)
expect(server_chain).to receive(:remove)
.with(described_class::Middleware::Server)
expect(server_chain).to receive(:add)
.with(described_class::Middleware::Server,
an_instance_of(
described_class::Configuration
))
described_class.register
end
it 'should register client middleware' do
client_chain = double('Sidekick::MiddlewareChain')
config = double('Sidekiq')
allow(config).to receive(:server_middleware)
allow(config).to receive(:client_middleware).and_yield(client_chain)
allow(Sidekiq).to receive(:configure_server).and_yield(config)
expect(client_chain).to receive(:remove)
.with(described_class::Middleware::Client)
expect(client_chain).to receive(:add)
.with(described_class::Middleware::Client,
an_instance_of(
described_class::Configuration
))
described_class.register
end
end
context 'when sidekiq not run as a server' do
it 'should register client middleware' do
client_chain = double('Sidekick::MiddlewareChain')
config = double('Sidekiq')
allow(config).to receive(:client_middleware).and_yield(client_chain)
allow(Sidekiq).to receive(:configure_client).and_yield(config)
expect(client_chain).to receive(:remove)
.with(described_class::Middleware::Client)
expect(client_chain).to receive(:add)
.with(described_class::Middleware::Client,
an_instance_of(
described_class::Configuration
))
described_class.register
end
end
end
end
|
class Word < ActiveRecord::Base
belongs_to :category
before_create :check_translation
before_update :track_changes
validates :name, presence: true, uniqueness: true, allow_blank: false
def self.search(query)
if query
where("name like ?", "%#{query}%")
else
all
end
end
def check_translation
self.displayed = translation.present? ? false : true
self
end
def track_changes
TranslationMailer.notification_email(mail).deliver_now if (self.displayed_changed? && self.displayed == false)
self
end
def check_translation
self.displayed = translation.present? ? false : true
self
end
end |
#!/usr/bin/env ruby
# encoding: utf-8
# from http://amqp.rubyforge.org/classes/MQ/Exchange.html
require "bundler"
Bundler.setup
require "amqp"
EventMachine.run do
AMQP.start do |connection|
channel = AMQP::Channel.new(connection)
exchange = channel.topic("stocks")
keys = ["stock.us.aapl", "stock.de.dax"]
EventMachine.add_periodic_timer(1) do # every second
puts
exchange.publish(10+rand(10), :routing_key => keys[rand(2)])
end
# match against one dot-separated item
channel.queue("us stocks").bind(exchange, :key => "stock.us.*").subscribe do |price|
puts "us stock price [#{price}]"
end
# match against multiple dot-separated items
channel.queue("all stocks").bind(exchange, :key => "stock.#").subscribe do |price|
puts "all stocks: price [#{price}]"
end
# require exact match
channel.queue("only dax").bind(exchange, :key => "stock.de.dax").subscribe do |price|
puts "dax price [#{price}]"
end
end
end
|
class Fabric < ActiveRecord::Base
belongs_to :supplier
mount_uploader :image, ImageUploader
validates :name, :price, presence: true
end
|
class Amazon
def initialize
@request = Vacuum.new
@request.configure(
aws_access_key_id:"#{ENV['AK']}",
aws_secret_access_key: "#{ENV['SAK']}",
associate_tag: 'bioim-20'
)
end
def itemresponse(pin)
params = {'ItemId' => "#{pin}",
'ResponseGroup' => "ItemAttributes, Images, Offers, Reviews, EditorialReview, Similarities"}
begin
response = @request.item_lookup(query: params)
response.parse
rescue
nil
end
end
def cartcreate(pin, quantity)
params = {
'Item.1.ASIN' => "#{pin}",
'Item.1.Quantity' => quantity
}
response = @request.cart_create(query: params)
response.parse
end
def cartadd(pin, id, hmac, quantity)
params = {
'Item.1.ASIN' => "#{pin}",
'Item.1.Quantity' => quantity,
'CartId' => "#{id}",
'HMAC' => "#{hmac}",
}
response = @request.cart_add(query: params)
response.parse
end
def cartclear(id, hmac)
params = {
'CartId' => "#{id}",
'HMAC' => "#{hmac}",
}
response = @request.cart_clear(query: params)
response.parse
end
def cartmodify(cartid, hmac, itemid, quantity)
params = {
'CartId' => "#{cartid}",
'HMAC' => "#{hmac}",
'Item.1.CartItemId' => "#{itemid}",
'Item.1.Quantity' => quantity,
}
response = @request.cart_modify(query: params)
response.parse
end
end
|
class PricesController < ApplicationController
def create
@price = Price.new(price_params)
respond_to do |format|
if @price.save
@price.ingredient.price = @price.price
@price.ingredient.save
format.html { redirect_to ingredient_path(@price.ingredient), notice: 'Precio actualizado exitosamente!' }
end
end
end
private
def price_params
params.require(:price).permit(:price, :ingredient_id)
end
end |
class ForecastDisplay
include Observer, DisplayElement
attr_reader :current_pressure, :last_pressure
def initialize(weather_data)
@current_pressure = 29.92
@weather_data = weather_data
@weather_data.register_observer(self)
end
def update(temperature, humidity, pressure)
@last_pressure = current_pressure
@current_pressure = pressure
display
end
def display
print "Forecast: "
if current_pressure > last_pressure
puts "Improving weather on the way!"
elsif current_pressure == last_pressure
puts "More of the same"
elsif current_pressure < last_pressure
puts "Watch out for cooler, rainy weather"
end
end
end
|
require 'spec_helper'
require 'digest/md5'
describe 'db.rake' do
let(:dummy_env) { 'dummy_env' }
let(:dummy_db_name) { "db_#{dummy_env}" }
after :each do
FileUtils.rm(dummy_db_name) if File.exists?(dummy_db_name)
end
describe 'db:drop' do
context 'database exists' do
before :each do
within_environment(dummy_env) { execute_rake('db:create') }
end
it 'drops the database' do
within_environment(dummy_env) do
expect(File.exists?(dummy_db_name)).to eq(true)
execute_rake('db:drop')
expect(File.exists?(dummy_db_name)).to eq(false)
end
end
end
context 'database does not exist' do
it 'does nothing' do
within_environment(dummy_env) do
execute_rake('db:drop')
expect(File.exists?(dummy_db_name)).to eq(false)
end
end
end
end
describe 'db:backup' do
before :each do
FileUtils.rm_rf('db/backups/test') if File.directory?('db/backups/test')
end
it 'creates a gzip archive file of a dump' do
expect(File.exists?('db/backups/test/db_test_20160402000438.bak.gz')).to eq(false)
Timecop.freeze(DateTime.parse('2016-04-02T00:04:38+00:00')) do
FactoryGirl.create(:card)
expect(Card.find_by_name('Dark Magician')).not_to eq(nil)
execute_rake('db:backup')
end
expect(File.exists?('db/backups/test/db_test_20160402000438.bak.gz')).to eq(true)
expect(Digest::MD5.file('db/backups/test/db_test_20160402000438.bak.gz').to_s).to eq('ef58fe8dc7b627c9b91e1fedc25a9a47')
end
end
describe 'db:restore' do
let(:source) { File.join('spec/samples/lib/tasks', backup_name) }
let(:temp_file) { File.join('tmp', backup_name) }
let(:unzipped_temp_file) { File.join('tmp', 'db_dummy_env_20160402203442.bak') }
let(:backup_name) { 'db_dummy_env_20160402203442.bak.gz' }
context 'database already exists' do
before :each do
within_environment(dummy_env) do
execute_rake("db:reset")
end
end
it 'does not restore' do
within_environment(dummy_env) do
execute_rake("db:restore", {source: source})
expect(File.exists?(source)).to eq(true)
[temp_file, unzipped_temp_file].each do |file|
expect(File.exists?(file)).to eq(false)
end
expect(Card.count).to eq(0)
end
end
end
context 'database does not exist' do
let(:properties_as_json) do
[{"id"=>1, "name"=>"element", "value"=>"DARK", "card_id"=>1},
{"id"=>2, "name"=>"level", "value"=>"7", "card_id"=>1},
{"id"=>3, "name"=>"attack", "value"=>"2500", "card_id"=>1},
{"id"=>4, "name"=>"defense", "value"=>"2100", "card_id"=>1},
{"id"=>5, "name"=>"species", "value"=>"Spellcaster", "card_id"=>1}]
end
let(:cards_as_json) do
[{"id"=>1, "name"=>"Dark Magician", "serial_number"=>"46986414", "description"=>"The ultimate wizard in terms of attack and defense.", "category"=>"Normal"}]
end
let(:artworks_as_json) do
[{"id"=>1, "image_path"=>"tmp/pictures/DarkMagician-OW.png", "card_id"=>1},
{"id"=>2, "image_path"=>"tmp/pictures/DarkMagician-OW-2.png", "card_id"=>1},
{"id"=>3, "image_path"=>"tmp/pictures/DarkMagician-TF05-JP-VG.png", "card_id"=>1},
{"id"=>4, "image_path"=>"tmp/pictures/DarkMagician-TF05-JP-VG-2.png", "card_id"=>1},
{"id"=>5, "image_path"=>"tmp/pictures/DarkMagician-TF05-JP-VG-3.png", "card_id"=>1},
{"id"=>6, "image_path"=>"tmp/pictures/DarkMagician-TF05-JP-VG-4.png", "card_id"=>1},
{"id"=>7, "image_path"=>"tmp/pictures/DarkMagician-TF05-JP-VG-5.png", "card_id"=>1}]
end
before :each do
within_environment(dummy_env) do
execute_rake("db:drop")
end
end
it 'copies and unzips the archive file, restores the data, and then removes the copy' do
within_environment(dummy_env) do
execute_rake("db:restore", {source: source})
expect(File.exists?(source)).to eq(true)
[temp_file, unzipped_temp_file].each do |file|
expect(File.exists?(file)).to eq(false)
end
expect(Card.all.as_json).to match_array(cards_as_json)
expect(Property.all.as_json).to match_array(properties_as_json)
expect(Artwork.all.as_json).to match_array(artworks_as_json)
expect_all_other_tables_to_be_empty([Card, Monster, Property, Artwork])
end
end
end
end
end
|
class Game
attr_reader :towers
def initialize(towers = [[3,2,1], [], []])
@towers = towers
end
def won?
return true if @towers[1] == [3,2,1] || @towers[2] == [3,2,1]
false
end
#[[3,2,1], [], []]) move(0, 1) [[3,2], [1], []])
def move(start_pos, end_pos)
if valid_move?(start_pos, end_pos)
@towers[end_pos] << @towers[start_pos].pop
else
puts "Invalid move!"
self.play
end
end
#
def valid_move?(start_pos, end_pos)
return true if @towers[end_pos].empty?
return false if @towers[start_pos].empty?
@towers[end_pos].last > @towers[start_pos].last ? true : false
end
def play
self.display
until self.won?
puts 'Please enter in the tower number to take a disk from'
move_res = gets.chomp.to_i
puts 'Please enter in the tower number to put the disk to'
place_res = gets.chomp.to_i
self.move(move_res, place_res)
self.display
end
puts 'You won!'
end
def display
@towers.each_with_index do |tower, i|
puts " tower #{i}:#{tower.join(' ')}"
end
end
end
#load "hanoi.rb"
|
require "spec_helper"
RSpec.describe OmniAuth::Strategies::Ibmid do
subject { OmniAuth::Strategies::Ibmid.new({}) }
context "client options" do
it "should have correct site" do
expect(subject.options.client_options.site).to eq(
"https://login.ibm.com"
)
end
it "should have correct authorization url path" do
expect(subject.options.client_options.authorize_url).to eq(
"https://login.ibm.com/oidc/endpoint/default/authorize"
)
end
it "should have correct token url path" do
expect(subject.options.client_options.token_url).to eq(
"https://login.ibm.com/oidc/endpoint/default/token"
)
end
end
end
|
require 'bundler'
Bundler.require
# $: << '/git/spdy/lib'
#
# require 'ffi-rzmq'
# require 'spdy'
class Worker
def initialize(opts = {})
@worker_identity = opts[:identity]
ctx = ZMQ::Context.new(1)
@conn = ctx.socket(ZMQ::XREP)
@conn.setsockopt(ZMQ::IDENTITY, opts[:identity])
@conn.connect(opts[:route])
@stream_id = nil
@headers = {}
@body = ''
@p = SPDY::Parser.new
@p.on_headers_complete do |stream, astream, priority, head|
@stream_id = stream
@headers = head
end
@p.on_body do |stream, body|
@body << body
end
@p.on_message_complete do |stream|
status, head, body = response(@headers, @body)
synreply = SPDY::Protocol::Control::SynReply.new
headers = {'status' => status.to_s, 'version' => 'HTTP/1.1'}.merge(head)
synreply.create(:stream_id => @stream_id, :headers => headers)
@conn.send_string(@identity, ZMQ::SNDMORE)
@conn.send_string(synreply.to_binary_s)
# Send body & close connection
resp = SPDY::Protocol::Data::Frame.new
resp.create(:stream_id => @stream_id, :flags => 1, :data => body)
@conn.send_string(@identity, ZMQ::SNDMORE)
@conn.send_string(resp.to_binary_s)
end
end
def run
loop do
@identity = @conn.recv_string()
delimiter = @conn.recv_string()
head = @conn.recv_string()
body = @conn.recv_string()
@p << head
@p << body
end
end
end |
module Sequel
module Extensions
module Honeycomb
class << self
attr_accessor :client
attr_reader :builder
attr_accessor :logger
def included(klazz)
@logger ||= ::Honeycomb.logger if defined?(::Honeycomb.logger)
if @client
debug "initialized with #{@client.class.name} explicitly provided"
elsif defined?(::Honeycomb.client)
debug "initialized with #{::Honeycomb.client.class.name} from honeycomb-beeline"
@client = ::Honeycomb.client
else
raise "Please set #{self.name}.client before using this extension"
end
@builder ||= @client.builder.add(
'meta.package' => 'sequel',
'meta.package_version' => Sequel::VERSION,
'type' => 'db',
)
end
private
def debug(msg)
@logger.debug("#{self.name}: #{msg}") if @logger
end
end
def builder
Sequel::Extensions::Honeycomb.builder
end
def execute(sql, opts=OPTS, &block)
event = builder.event
event.add_field 'db.table', first_source_table.to_s rescue nil
event.add_field 'db.sql', sql
event.add_field 'name', query_name(sql)
start = Time.now
with_tracing_if_available(event) do
super
end
rescue Exception => e
if event
event.add_field 'db.error', e.class.name
event.add_field 'db.error_detail', e.message
end
raise
ensure
if start && event
finish = Time.now
duration = finish - start
event.add_field 'duration_ms', duration * 1000
event.send
end
end
private
def query_name(sql)
sql.sub(/\s+.*/, '').upcase
end
def with_tracing_if_available(event)
# return if we are not using the ruby beeline
return yield unless defined?(::Honeycomb)
# beeline version <= 0.5.0
if ::Honeycomb.respond_to? :trace_id
trace_id = ::Honeycomb.trace_id
event.add_field 'trace.trace_id', trace_id if trace_id
span_id = SecureRandom.uuid
event.add_field 'trace.span_id', span_id
::Honeycomb.with_span_id(span_id) do |parent_span_id|
event.add_field 'trace.parent_id', parent_span_id
yield
end
# beeline version > 0.5.0
elsif ::Honeycomb.respond_to? :span_for_existing_event
::Honeycomb.span_for_existing_event(event, name: nil, type: 'db') do
yield
end
# fallback if we don't detect any known beeline tracing methods
else
yield
end
end
end
Sequel::Dataset.register_extension(:honeycomb, Honeycomb)
end
end
|
class ChangeEntryAmountToDecimal < ActiveRecord::Migration[5.2]
def change
remove_column :entries, :amount, :string
add_column :entries, :amount, :decimal, precision: 8, scale: 2
end
end
|
require 'open-uri'
module CoinBuilder
class Runner
def self.run!
new.run!
end
attr_reader :coin_hash
def initialize
@coin_hash = {}.with_indifferent_access
end
def run!
load_data
@coin_hash.each do |symbol, data|
puts "Adding #{symbol}, data: #{data}"
Coin.create!(data) do |coin|
coin.score!
end
end
end
def load_data
puts "Loading from CryptoCompare..."
CryptoCompare.data.each do |symbol, data|
@coin_hash[symbol] ||= {}
hash_entry = @coin_hash[symbol]
hash_entry[:symbol] = symbol
hash_entry[:name] = data.fetch("FullName")
hash_entry[:proof_type] = data.fetch("ProofType")
hash_entry[:is_fully_premined] = data.fetch("FullyPremined").to_i != 0 if data.fetch("FullyPremined")
hash_entry[:cryptocompare_id] = data.fetch("Id")
hash_entry[:cryptocompare_rank] = data.fetch("SortOrder")
@coin_hash[symbol]
end
puts "@coin_hash size #{@coin_hash.size}"
puts "Loading from CoinMarketCap..."
CoinMarketCap.data.each do |data|
symbol = data.fetch("symbol")
if hash_entry = @coin_hash[symbol]
hash_entry[:coinmarketcap_id] = data.fetch("id")
hash_entry[:coinmarketcap_rank] = data.fetch("rank").to_i
hash_entry[:last_price_btc] = data.fetch("price_btc")
hash_entry[:market_cap] = data.fetch("market_cap_usd") if data.fetch("market_cap_usd").present?
hash_entry[:available_supply] = data.fetch("available_supply") if data.fetch("available_supply").present?
hash_entry[:total_supply] = data.fetch("total_supply") if data.fetch("total_supply").present?
end
end
load_full_data_from_storage.each do |symbol, data|
if hash_entry = @coin_hash[symbol]
hash_entry[:last_volume_btc] = data[:btc_volume]
end
end
load_snapshot_data_from_storage.each do |symbol, data|
if hash_entry = @coin_hash[symbol]
hash_entry[:exchanges] = data["Data"]["Exchanges"].map{|h| h["MARKET"]} if data["Data"]["Exchanges"]
end
end
end
def extract_coin_activity
{}.tap do |hash|
Coin.positive_fa_score.find_in_batches(batch_size: 50) do |group|
symbols = group.map(&:symbol).join(',')
puts "got symbols: #{symbols}"
add_coins_to_storage_hash(symbols, hash)
end
# loop
# add hash entry for volume
end
end
# { "RAW" => { "LTC" => "BTC" => {data} } }
# data:
# {"TYPE"=>"5",
# "MARKET"=>"CCCAGG",
# "FROMSYMBOL"=>"BOST",
# "TOSYMBOL"=>"BTC",
# "FLAGS"=>"4",
# "PRICE"=>1.76e-06,
# "LASTUPDATE"=>1518064906,
# "LASTVOLUME"=>1034.93181818,
# "LASTVOLUMETO"=>0.001821479999997,
# "LASTTRADEID"=>"7429",
# "VOLUMEDAY"=>3050.55681818,
# "VOLUMEDAYTO"=>0.004401479999997,
# "VOLUME24HOUR"=>1034.93181818,
# "VOLUME24HOURTO"=>0.001821479999997,
# "OPENDAY"=>1.25e-06,
# "HIGHDAY"=>1.76e-06,
# "LOWDAY"=>1.25e-06,
# "OPEN24HOUR"=>1.28e-06,
# "HIGH24HOUR"=>1.76e-06,
# "LOW24HOUR"=>1.28e-06,
# "LASTMARKET"=>"CCEX",
# "CHANGE24HOUR"=>4.800000000000001e-07,
# "CHANGEPCT24HOUR"=>37.50000000000001,
# "CHANGEDAY"=>5.1e-07,
# "CHANGEPCTDAY"=>40.8,
# "SUPPLY"=>16961292.2854024,
# "MKTCAP"=>29.851874422308224,
# "TOTALVOLUME24H"=>1034.93181818,
# "TOTALVOLUME24HTO"=>0.001821479999997}
def add_coins_to_storage_hash(symbols, hash)
data = JSON.parse(open("https://min-api.cryptocompare.com/data/pricemultifull?fsyms=#{symbols}&tsyms=BTC").read)
data["RAW"].each do |symbol, markets_hash|
stats = markets_hash["BTC"]
hash[symbol] = { btc_volume: stats["TOTALVOLUME24HTO"] }
end
end
def add_snapshots_to_storage_hash
{}.tap do |hash|
Coin.positive_fa_score.find_in_batches(batch_size: 10) do |group|
group.each do |coin|
symbol = coin.symbol
puts "adding: #{symbol}"
data = JSON.parse(open("https://www.cryptocompare.com/api/data/coinsnapshot/?fsym=#{symbol}&tsym=BTC").read)
hash[symbol] = data
end
puts "sleeping 5 secs..."
sleep(5)
end
end
end
def local_store_snapshot_data!
hash = add_snapshots_to_storage_hash
File.open(LOCAL_SNAPSHOT_STORAGE_PATH,'wb'){|f| f.write(hash)}
end
LOCAL_VOLUME_STORAGE_PATH = Rails.root.join("data","coin_activity_data.txt")
LOCAL_SNAPSHOT_STORAGE_PATH = Rails.root.join("data","coin_snapshot_data.txt")
def local_store_volume_data!
hash = extract_coin_activity
File.open(LOCAL_VOLUME_STORAGE_PATH,'wb'){|f| f.write(hash)}
end
def load_full_data_from_storage
eval(File.open(LOCAL_VOLUME_STORAGE_PATH).read).with_indifferent_access
end
def load_snapshot_data_from_storage
eval(File.open(LOCAL_SNAPSHOT_STORAGE_PATH).read).with_indifferent_access
end
end
# TRI criteria
#
# DB - modeling
#
# symbol
# name
# proof_type # cc
# total_supply # cc
# is_fully_premined # cc
# cryptocompare_id
# cryptocompare_rank
#
# {"id"=>"bitcoin",
# "name"=>"Bitcoin",
# "symbol"=>"BTC",
# "rank"=>"1",
# "price_usd"=>"8296.14",
# "price_btc"=>"1.0",
# "24h_volume_usd"=>"9676000000.0",
# "market_cap_usd"=>"139819717254",
# "available_supply"=>"16853587.0",
# "total_supply"=>"16853587.0",
# "max_supply"=>"21000000.0",
# "percent_change_1h"=>"-1.03",
# "percent_change_24h"=>"2.1",
# "percent_change_7d"=>"-8.52",
# "last_updated"=>"1518123869"}
class CoinMarketCap
def self.data
@data ||= JSON.parse(open("https://api.coinmarketcap.com/v1/ticker/?limit=0").read)
end
end
class CryptoCompare
# ["Response", "Message", "BaseImageUrl", "BaseLinkUrl", "DefaultWatchlist", "Data", "Type"]
# ["BTC",
# {"Id"=>"1182",
# "Url"=>"/coins/btc/overview",
# "ImageUrl"=>"/media/19633/btc.png",
# "Name"=>"BTC",
# "Symbol"=>"BTC",
# "CoinName"=>"Bitcoin",
# "FullName"=>"Bitcoin (BTC)",
# "Algorithm"=>"SHA256",
# "ProofType"=>"PoW",
# "FullyPremined"=>"0",
# "TotalCoinSupply"=>"21000000",
# "PreMinedValue"=>"N/A",
# "TotalCoinsFreeFloat"=>"N/A",
# "SortOrder"=>"1",
# "Sponsored"=>false}]
def self.data
@data ||= JSON.parse(open("https://www.cryptocompare.com/api/data/coinlist/").read).fetch("Data")
end
# {"Response"=>"Success",
# "Message"=>"This api will soon move to mi-api path.",
# "Data"=>
# {"Algorithm"=>nil,
# "ProofType"=>nil,
# "BlockNumber"=>0,
# "NetHashesPerSecond"=>0.0,
# "TotalCoinsMined"=>16329896.0,
# "BlockReward"=>0.0,
# "AggregatedData"=>
# {"TYPE"=>"5",
# "MARKET"=>"CCCAGG",
# "FROMSYMBOL"=>"SIB",
# "TOSYMBOL"=>"BTC",
# "FLAGS"=>"4",
# "PRICE"=>"0.0002426",
# "LASTUPDATE"=>"1518238643",
# "LASTVOLUME"=>"198.00462552",
# "LASTVOLUMETO"=>"0.04811512",
# "LASTTRADEID"=>"6837787",
# "VOLUMEDAY"=>"37501.85951836003",
# "VOLUMEDAYTO"=>"8.921583767289063",
# "VOLUME24HOUR"=>"91188.75248019001",
# "VOLUME24HOURTO"=>"21.346147605396464",
# "OPENDAY"=>"0.0002395",
# "HIGHDAY"=>"0.000243",
# "LOWDAY"=>"0.0002326",
# "OPEN24HOUR"=>"0.0002257",
# "HIGH24HOUR"=>"0.0002426",
# "LOW24HOUR"=>"0.000222",
# "LASTMARKET"=>"BitTrex"},
# "Exchanges"=>
# [{"TYPE"=>"2",
# "MARKET"=>"CCEX",
# "FROMSYMBOL"=>"SIB",
# "TOSYMBOL"=>"BTC",
# "FLAGS"=>"4",
# "PRICE"=>"0.000205",
# "LASTUPDATE"=>"1518088556",
# "LASTVOLUME"=>"4.54133562",
# "LASTVOLUMETO"=>"0.0009309738021",
# "LASTTRADEID"=>"10083",
# "VOLUME24HOUR"=>"0",
# "VOLUME24HOURTO"=>"0",
# "OPEN24HOUR"=>"0.000205",
# "HIGH24HOUR"=>"0.000205",
# "LOW24HOUR"=>"0.000205"},
# {"TYPE"=>"2",
# "MARKET"=>"BitTrex",
# "FROMSYMBOL"=>"SIB",
# "TOSYMBOL"=>"BTC",
# "FLAGS"=>"2",
# "PRICE"=>"0.000243",
# "LASTUPDATE"=>"1518238643",
# "LASTVOLUME"=>"198.00462552",
# "LASTVOLUMETO"=>"0.04811512",
# "LASTTRADEID"=>"6837787",
# "VOLUME24HOUR"=>"78042.49226867",
# "VOLUME24HOURTO"=>"18.30822443",
# "OPEN24HOUR"=>"0.000226",
# "HIGH24HOUR"=>"0.00024303",
# "LOW24HOUR"=>"0.00022238"},
# {"TYPE"=>"2",
# "MARKET"=>"Cryptopia",
# "FROMSYMBOL"=>"SIB",
# "TOSYMBOL"=>"BTC",
# "FLAGS"=>"4",
# "PRICE"=>"0.000241",
# "LASTUPDATE"=>"1518228176",
# "LASTVOLUME"=>"9.82562689",
# "LASTVOLUMETO"=>"0.00236798",
# "LASTTRADEID"=>"15182281760001",
# "VOLUME24HOUR"=>"1602.04619975",
# "VOLUME24HOURTO"=>"0.37494015",
# "OPEN24HOUR"=>"0.00022249",
# "HIGH24HOUR"=>"0.00024673",
# "LOW24HOUR"=>"0.00022249"},
# {"TYPE"=>"2",
# "MARKET"=>"BitSquare",
# "FROMSYMBOL"=>"SIB",
# "TOSYMBOL"=>"BTC",
# "FLAGS"=>"4",
# "PRICE"=>"0.00009524",
# "LASTUPDATE"=>"1461967161",
# "LASTVOLUME"=>"1050",
# "LASTVOLUMETO"=>"0.10000200000000001",
# "LASTTRADEID"=>"18865",
# "VOLUME24HOUR"=>"0",
# "VOLUME24HOURTO"=>"0",
# "OPEN24HOUR"=>"0.00009524",
# "HIGH24HOUR"=>"0.00009524",
# "LOW24HOUR"=>"0.00009524"},
# {"TYPE"=>"2",
# "MARKET"=>"LiveCoin",
# "FROMSYMBOL"=>"SIB",
# "TOSYMBOL"=>"BTC",
# "FLAGS"=>"4",
# "PRICE"=>"0.000238",
# "LASTUPDATE"=>"1518237856",
# "LASTVOLUME"=>"7.01705095",
# "LASTVOLUMETO"=>"0.0016700581261",
# "LASTTRADEID"=>"276054984",
# "VOLUME24HOUR"=>"11284.764553920002",
# "VOLUME24HOURTO"=>"2.606306828928371",
# "OPEN24HOUR"=>"0.00022225",
# "HIGH24HOUR"=>"0.000238",
# "LOW24HOUR"=>"0.00021849"},
# {"TYPE"=>"2",
# "MARKET"=>"Yobit",
# "FROMSYMBOL"=>"SIB",
# "TOSYMBOL"=>"BTC",
# "FLAGS"=>"4",
# "PRICE"=>"0.00023779",
# "LASTUPDATE"=>"1518238051",
# "LASTVOLUME"=>"10.57739936",
# "LASTVOLUMETO"=>"0.0025151997938144",
# "LASTTRADEID"=>"200003009",
# "VOLUME24HOUR"=>"639.7970969400001",
# "VOLUME24HOURTO"=>"0.14870118646809038",
# "OPEN24HOUR"=>"0.00022871",
# "HIGH24HOUR"=>"0.00023779",
# "LOW24HOUR"=>"0.00021393"}]},
# "Type"=>100}
end
end |
require 'simplepay/support/interval'
module Simplepay
module Support
class SubscriptionPeriod < Interval
ALLOWED_INTERVALS = Simplepay::Intervals + ['forever']
# Limited to 3 digits.
ALLOWED_QUANTITY_RANGE = (1...1000)
##
# See Simplepay::Support::Interval.to_s for more information.
#
# If the subscription lasts "forever" then Amazon does not need an
# interval string.
#
def to_s
super unless interval == 'forever'
end
end
end
end |
class HolidaySpirit
attr_reader :christmas
def initialize(christmas)
@christmas = christmas
end
def tree
"A Big bushy #{christmas.xmas_tree}, "
end
def drinks
"The smells of #{christmas.xmas_food} around the house fills your"
end
def spirit
"#{christmas.xmas_spirit} with Christmas Joy!!"
end
end
|
require 'abstract_unit'
class ReloaderTests < ActiveSupport::TestCase
Reloader = ActionController::Reloader
Dispatcher = ActionController::Dispatcher
class MyBody < Array
def initialize(&block)
@on_close = block
end
def foo
"foo"
end
def bar
"bar"
end
def close
@on_close.call if @on_close
end
end
def setup_and_return_body(app = lambda { })
Dispatcher.expects(:reload_application)
reloader = Reloader.new(app)
headers, status, body = reloader.call({ })
body
end
def test_it_reloads_the_application_before_the_request
Dispatcher.expects(:reload_application)
reloader = Reloader.new(lambda {
[200, { "Content-Type" => "text/html" }, [""]]
})
reloader.call({ })
end
def test_returned_body_object_always_responds_to_close
body = setup_and_return_body(lambda {
[200, { "Content-Type" => "text/html" }, [""]]
})
assert body.respond_to?(:close)
end
def test_returned_body_object_behaves_like_underlying_object
body = setup_and_return_body(lambda {
b = MyBody.new
b << "hello"
b << "world"
[200, { "Content-Type" => "text/html" }, b]
})
assert_equal 2, body.size
assert_equal "hello", body[0]
assert_equal "world", body[1]
assert_equal "foo", body.foo
assert_equal "bar", body.bar
end
def test_it_calls_close_on_underlying_object_when_close_is_called_on_body
close_called = false
body = setup_and_return_body(lambda {
b = MyBody.new do
close_called = true
end
[200, { "Content-Type" => "text/html" }, b]
})
body.close
assert close_called
end
def test_returned_body_object_responds_to_all_methods_supported_by_underlying_object
body = setup_and_return_body(lambda {
[200, { "Content-Type" => "text/html" }, MyBody.new]
})
assert body.respond_to?(:size)
assert body.respond_to?(:each)
assert body.respond_to?(:foo)
assert body.respond_to?(:bar)
end
def test_it_doesnt_clean_up_the_application_after_call
Dispatcher.expects(:cleanup_application).never
body = setup_and_return_body(lambda {
[200, { "Content-Type" => "text/html" }, MyBody.new]
})
end
def test_it_cleans_up_the_application_when_close_is_called_on_body
Dispatcher.expects(:cleanup_application)
body = setup_and_return_body(lambda {
[200, { "Content-Type" => "text/html" }, MyBody.new]
})
body.close
end
end
|
require 'yaml'
require 'set'
require 'find'
require 'net/ssh'
require 'net/scp'
require 'net/sftp'
require_relative 'target'
require_relative 'remote'
require_relative 'msg'
module Chamois
class Application
private
def files
Dir.glob('**/{*,.*}').reject { |f| File.directory? f }
end
def read_config(path)
y = File.read(path)
begin
config = YAML.load(y)
rescue
raise "Incorrect format of config file at #{path}"
end
config
end
def load_config!(path)
fail "Can't find config at #{path}" unless File.exist?(path)
fail "Can't read config file at #{path}" unless File.readable?(path)
read_config(path)
end
def load_config(path)
return {} unless File.exist?(path) && File.readable?(path)
read_config(path)
end
public
def initialize(stage)
stages = load_config!('_deploy/stages.yaml')
@stage = stages[stage]
fail 'Unknown stage' unless @stage
@targets = []
end
# Create connection to target and ready for commands
def connect
@stage.each do |name, config|
begin
remote = Remote.new(name, config)
@targets.push Target.new(remote)
rescue Exception => e
Msg.fail e
disconnect
return false
end
end
true
end
# Disconnect all targets
def disconnect
@targets.each(&:disconnect)
end
def deploy
rules_config = load_config('_deploy/rules.yaml')
release = Time.now.strftime("%Y-%m-%d_%H%M%S.%L").to_s
begin
@targets.each { |t| t.deploy(release, files, rules_config) }
Msg.ok('Deploy complete')
rescue Exception => e
Msg.fail e
end
end
def release
begin
@targets.each(&:release)
Msg.ok('Release complete')
rescue Exception => e
Msg.fail e
Msg.fail('WARNING! May be at inconsistent state!')
end
end
def rollback
begin
@targets.each(&:rollback)
Msg.ok('Rollback complete')
rescue Exception => e
Msg.fail e
Msg.fail('WARNING! May be at inconsistent state!')
end
end
end
end
|
require 'pry'
class Genre
attr_accessor :name
@@all = []
def initialize(name)
@name = name
@@all << self
end
def self.all
@@all
end
# iterates through all songs and finds the songs that belong
# to that genre
def songs
Song.all.select do |song|
song.genre == self
end
end
# iterates over the genre's collection of songs and collects
# the artist that owns each song
def artists
self.songs.map{|song| song.artist}
end
end |
# Simple Role Syntax
# ==================
# Supports bulk-adding hosts to roles, the primary server in each group
# is considered to be the first unless any hosts have the primary
# property set. Don't declare `role :all`, it's a meta role.
set :deploy_to, '/var/www/sos'
set :rails_env, 'production'
set :unicorn_path, "#{deploy_to}/current/config/unicorn/production.rb"
set :ip, "118.193.197.139"
set :user, 'hex'
set :unicorn_pid, "#{deploy_to}/current/tmp/pids/unicorn.pid"
role :app, fetch(:ip)
role :web, fetch(:ip)
role :db, fetch(:ip)
set :password, "hexiang2o!5"
# Extended Server Syntax
# ======================t
# This can be used to drop a more detailed server definition into the
# server list. The second argument is a, or duck-types, Hash and is
# used to set extended properties on the server.
set :unicorn_rack_env, "production"
set :unicorn_roles, :web
server fetch(:ip), user: fetch(:user), port: 22, password: fetch(:password), roles: %w{web} |
FactoryBot.define do
factory :currency do
trait :gbp do
code { "GBP" }
end
trait :eur do
code { "EUR" }
end
end
end
|
class PhoneNumber
def initialize(number)
@number = number
end
def number
number_1 = @number.delete "("
number_2 = number_1.delete ")"
number_3 = number_2.delete " "
number_4 = number_3.delete "."
number_5 = number_4.delete "-"
if number_5.chars.any? {|n| n.include? "a"}
'0000000000'
elsif number_5.length == 10
number_5
elsif number_5.length == 11 && number_5[0] == "1"
number_5[1..-1]
else
'0000000000'
end
end
def area_code
number[0..2]
end
def to_s
"(#{number[0..2]}) #{number[3..5]}-#{number[6..-1]}"
end
end |
require 'test_helper'
module KindleHighlightsAPI
class BookTest < MiniTest::Unit::TestCase
def test_from_page_creates_a_book_from_the_page
expectation = {
title: "Drawing on the Right Side of the Brain: The Definitive, 4th Edition",
highlight: "learning to draw, without doubt, causes new connections in the brain that can be useful over a lifetime for general thinking. Learning to see in a different way requires that you use your brain differently."
}
page = create_page_from_fixture(:highlights_page_1)
book = Book.from_page(page)
assert_equal expectation[:title], book.title
assert book.highlights.include?(expectation[:highlight])
end
private
def create_page_from_fixture(filename)
body = File.open("#{TEST_ROOT}/fixtures/html/#{filename.to_s}.html").read
mech = Mechanize.new
Mechanize::Page.new(nil, nil, body, nil, mech)
end
end
end
|
module APHT
def APHT::content_type(path)
ext = File.extname(path).split(".").last
CONTENT_TYPE_MAPPING.fetch(ext, DEFAULT_CONTENT_TYPE)
end
def APHT::securePath(request)
path = URI.unescape(URI(request).path)
clean = []
path.split("/").each do |part|
next if part.empty? || part == '.'
part == '..' ? clean.pop : clean << part
end
File.join(WEB_ROOT, *clean)
end
def APHT::streamFile(file, socket, code = "200 OK")
File.open(file, "rb") do |f1|
socket.print "HTTP/1.1 #{code}\r\n" +
"Content-Type: #{APHT::content_type(f1)}\r\n" +
"Content-Length: #{f1.size}\r\n" +
"Connection: close\r\n"
socket.print "\r\n"
IO.copy_stream(f1, socket)
end
end
end
|
require 'faraday'
require 'faraday_middleware'
require 'hashie/mash'
require 'cortex/faraday_middleware/response_failures'
require 'cortex/faraday_middleware/normalize_uri_path'
module Cortex
module Connection
def connection
options = {
:headers => {
:user_agent => "cortex-client-ruby - #{Cortex::VERSION}"
},
:url => base_url
}
if access_token.is_a?(OAuth2::AccessToken) && access_token.expired?
@access_token = get_cc_token
end
Faraday::Utils.default_uri_parser = Addressable::URI
Faraday.new options do |conn|
## Request middleware first:
conn.use Cortex::FaradayMiddleware::NormalizeURIPath
conn.request :oauth2, access_token.is_a?(OAuth2::AccessToken) ? access_token.token : access_token, token_type: 'param'
conn.request :json
## Response middleware second:
conn.response :mashify
conn.use Cortex::FaradayMiddleware::ResponseFailures
conn.response :json, :content_type => /\bjson$/
## Adapter always last:
conn.adapter Faraday.default_adapter
end
end
end
end
|
require 'rails_helper'
feature 'user', type: :feature do
feature 'ユーザー登録前' do
scenario '会員情報入力ができるか' do
visit new_user_registration_path
fill_in "user_nickname",with: "メルカリさん"
fill_in "user_email",with: "email@gmail.com"
fill_in "user_password",with: "abc1234"
fill_in "user_password_confirmation",with: "abc1234"
fill_in "user_last_name", with: "山田"
fill_in "user_first_name",with: "太郎"
fill_in "user_last_name_kana", with: "ヤマダ"
fill_in "user_first_name_kana", with: "タロウ"
select '2000', from: 'user_birthday_1i'
select '10', from: 'user_birthday_2i'
select '10', from: 'user_birthday_3i'
click_on "次へ進む"
expect(page).to have_content("お届け先情報入力")
end
scenario 'ログインできないこと' do
visit root_path
click_on "ログイン"
fill_in "user_email", with: "bbb@gmail.com"
fill_in "user_password", with: "1111111"
click_on "ログイン"
expect(page).to have_content("アカウントをお持ちでない方はこちら")
end
scenario '商品出品ボタンを押すとログインページに遷移すること' do
visit root_path
click_on "出品する"
expect(page).to have_content("アカウントをお持ちでない方はこちら")
end
end
feature 'ユーザー登録後' do
let(:user) {create(:user)}
background 'ログインできるか' do
visit root_path
click_on "ログイン"
fill_in "user_email", with: user.email
fill_in "user_password", with: user.password
click_on "ログイン"
end
scenario 'ログインできているとヘッダーにマイページが表示されること' do
expect(page).to have_content "マイページ"
end
scenario 'ログアウトができること' do
visit user_path(user)
click_on "ログアウト"
expect(page).to have_content "新規会員登録"
end
scenario '商品出品ボタンを押すと出品ページにに遷移するか' do
click_on "出品する"
expect(page).to have_content("出品画像")
end
end
end |
# frozen_string_literal: true
module Files
class OauthRedirect
attr_reader :options, :attributes
def initialize(attributes = {}, options = {})
@attributes = attributes || {}
@options = options || {}
end
# string - Redirect URL
def redirect_uri
@attributes[:redirect_uri]
end
end
end
|
class AddHoursToLogEntries < ActiveRecord::Migration
def change
add_column :log_entries, :hours, :float
end
end
|
require 'rails_helper'
RSpec.describe Reservation, type: :model do
let(:reservation_instance) { build(:reservation) }
it "has a valid factory" do
expect(reservation_instance).to respond_to(:order)
expect(reservation_instance).to respond_to(:pickup_time)
end
it "reservation validates attributes" do
expect(reservation_instance).to validate_presence_of(:order)
expect(reservation_instance).to validate_presence_of(:pickup_time)
end
it "can generate correct time range" do
result = Reservation.generate_available_dates
start = DateTime.now.beginning_of_day + 10.hour + 1.day
expect(result).to include(start)
expect(result.length).to eq(6)
end
it "can find all booked times in the database" do
create(:reservation)
time = DateTime.now.beginning_of_day + 10.hour + 1.day
expect(Reservation.all.length).to eq(1)
expect(Reservation.get_booked_times.length).to eq(1)
expect(Reservation.get_booked_times.last).to eq(time)
expect(Reservation.get_all_dates.length).to eq(6)
end
end
|
require 'rails_helper'
RSpec.describe Project, type: :model do
it { is_expected.to validate_presence_of(:name) }
it { is_expected.to have_many(:member_projects) }
it { is_expected.to have_many(:members).through(:member_projects) }
end
|
module GodaddyApi
class KeyMapping
include Kartograph::DSL
kartograph do
mapping Key
root_key plural: 'results', scopes: [:read]
property :keyId, :name, :key, scopes: [:read]
property :key, :name, scopes: [:create]
end
end
end
|
require 'command_line_reporter'
class HelloSignDownloader
class Reporter
include CommandLineReporter
def initialize(documents)
@documents = documents
end
def run
table :border => true do
row do
column 'Document ID', width: 40, bold: true, align: 'center'
column 'Complete', width: 30, align: 'center'
column 'Declined', width: 15, align: 'center'
column 'Has Errors', width: 15, align: 'center'
end
if @documents.any?
@documents.each do |d|
row do
column d.signature_request_id
column d.is_complete
column d.is_declined
column d.has_error
end
end
else
row do
column 'No data available'
end
end
end
end
end
end
|
class EmployeePlannedHoliday < ApplicationRecord
belongs_to :employee
validates :holiday_date, presence: true
end
|
class ConsoleOwnershipController < ApplicationController
before_action :signed_in_user
before_action :correct_user, only: [:edit, :update, :destroy, :show]
def show
@console = ConsoleOwnership.find_by(id: params[:id])
@user = User.find_by(remember_token: cookies[:remember_token])
end
def new
@ownership = ConsoleOwnership.new
@console = Consoles.find_by(id: params[:id])
@quality_array = Quality.all.map {|quality| [quality.quality, quality.id]}
@quality_array.insert(0, "")
end
def create
@user = User.find_by(remember_token: cookies[:remember_token])
@ownership = ConsoleOwnership.new(user_id: current_user().id,
consoles_id: params[:console_ownership][:consoles_id],
own: 1,
complete: params[:console_ownership][:complete],
box_condition: params[:console_ownership][:box_condition],
console_condition: params[:console_ownership][:console_condition],
manual_condition: params[:console_ownership][:manual_condition],
inserts_condition: params[:console_ownership][:inserts_condition],
notes: params[:console_ownership][:notes])
if @ownership.save
redirect_to @ownership
else
end
end
def edit
@ownership = ConsoleOwnership.find(params[:id])
@console = Consoles.find(ConsoleOwnership.find(params[:id]).consoles_id)
@quality_array = Quality.all.map {|quality| [quality.quality, quality.id]}
@quality_array.insert(0, "")
end
def update
@ownership = ConsoleOwnership.find(params[:id])
@console = Consoles.find(ConsoleOwnership.find(params[:id]).consoles_id)
if @ownership.update_attributes(user_id: current_user().id,
consoles_id: ConsoleOwnership.find(params[:id]).consoles_id,
own: 1,
complete: params[:console_ownership][:complete],
box_condition: params[:console_ownership][:box_condition],
console_condition: params[:console_ownership][:console_condition],
manual_condition: params[:console_ownership][:manual_condition],
inserts_condition: params[:console_ownership][:inserts_condition],
notes: params[:console_ownership][:notes])
flash[:success] = @console.eng_name + " Successfully Updated"
redirect_to @ownership
else
render 'edit'
end
end
def destroy
ConsoleOwnership.delete(params[:id])
redirect_to inventory_consoles_path
end
private
def ownership_params
params.require(:ownership).permit(:ean, :eng_name, :jap_name, :system, :region, :image)
end
def delete_params
params.require(:ownership).permit(:id, :ean, :eng_title, :jap_title, :system, :region, :image)
end
# Before filters
def signed_in_user
unless signed_in?
store_location
redirect_to signIn_url, notice: "Please sign in."
end
end
def correct_user
@user = User.find(ConsoleOwnership.find(params[:id]).user_id)
redirect_to current_user, notice: "Sorry, you can't edit someone else's inventory" unless current_user?(@user)
end
end
|
# == Schema Information
#
# Table name: restaurants
#
# id :integer not null, primary key
# name :string(255)
# address :string(255)
# cuisine :string(255)
# thumbs_down :boolean default(FALSE)
# lat :float
# long :float
# value_rating :integer
#
require 'spec_helper'
describe Restaurant do
describe '.new' do
it 'creates an instance of Restaurant' do
restaurant = Restaurant.new
expect(restaurant).to be_an_instance_of(Restaurant)
end
end
describe '.create' do
it 'has a name' do
restaurant = Restaurant.create(name: 'Hundred Acres')
expect(restaurant.id).to_not be nil
end
it 'fails validation if name is blank' do
restaurant = Restaurant.create
expect(restaurant.id).to be nil
end
end
describe '#reviews' do
it 'has reviews' do
review = Review.new
restaurant = Restaurant.new
restaurant.reviews << review
expect(restaurant.reviews.first).to be_an_instance_of(Review)
end
end
end
|
MiEdificioServer::App.controllers :users, parent: :buildings do
get :index, provides: [:json] do
params_keys = [:building_id]
@building_users = BuildingUser.where(params.slice(*params_keys))
jbuilder 'building_users/index'
end
get :show, '', with: :id, provides: [:json] do
params_keys = [:building_id, :id]
@building_user = BuildingUser.where(params.slice(*params_keys)).first
respond_not_nil(@building_user) do
jbuilder 'building_users/show'
end
end
post :create, '', provides: [:json] do
params_keys = [:building_id, :name, :apartment, :role_description]
attributes = params.slice(*params_keys).merge(building_creator: false)
building = Building.find_by_id(params[:building_id])
if (building.nil?)
return respond_not_found
elsif (building.building_users.count == 0)
attributes[:building_creator] = true
end
@building_user = BuildingUser.create(attributes)
jbuilder 'building_users/show'
end
put :update, '', with: :id, provides: [:json] do
params_keys = [:name, :apartment, :role_description]
attributes = params.slice(*params_keys)
@building_user = BuildingUser.update(params[:id], attributes)
respond_not_nil(@building_user) do
jbuilder 'building_users/show'
end
end
delete :destroy, '', with: :id, provides: [:json] do
params_keys = [:building_id, :id]
@building_user = BuildingUser.where(params.slice(*params_keys)).delete_all
respond_if_condition(@building_user.count > 0) do
respond_no_content
end
end
end
|
module Measurable
module ClassMethods
def define_measureable_methods(metrics, cycles, measurements)
metric_cycle_measures(metrics, cycles, measurements)
reading_nested_arrays(measurements)
measurement_nested_arrays(measurements)
measurement_hashes(measurements)
measurement_methods(measurements)
end
def metric_cycle_measures(metrics, cycles, measurements)
metrics.each do |metric|
cycles.each do |cycle|
measurements.each do |measurement|
define_method("#{metric}_#{cycle}_#{measurement}") do
array = self.send("get_cycle_#{measurement}s", cycle)
self.send(metric, array)
end
end
end
end
end
def reading_nested_arrays(measurements)
define_method("reading_nested_array") do
readings.pluck(:created_at, *measurements).compact
end
define_method("reverse_reading_nested_array") do |_readings|
_readings.order(created_at: :desc).pluck(:created_at, *measurements).compact
end
end
def measurement_nested_arrays(measurements)
measurements.each do |measurement|
define_method("#{measurement}_nested_array") do
readings.pluck(:created_at, measurement).compact
end
end
end
def measurement_hashes(measurements)
measurements.each do |measurement|
define_method("#{measurement}_hash") do
send("#{measurement}_nested_array").each_with_object({}) do |pair, hsh|
key, value = *pair
hsh[key] = value
end
end
end
end
def measurement_methods(measurements)
measurements.each do |measurement|
define_method("#{measurement}s") do
readings.pluck(measurement).compact
end
end
end
end
module InstanceMethods
def avg(array)
return nil if array.empty?
array.sum / array.size
end
def max(array)
array.max
end
def min(array)
array.min
end
def get_cycle_temps(cycle)
temp_array = []
self.temp_nested_array.each do |time, temp|
hour = time.hour + time_offset_in_hours
temp_array << temp if self.send("#{cycle}_time_hours_include?", hour)
end
temp_array
end
def get_cycle_outdoor_temps(cycle)
outdoor_temp_array = []
self.outdoor_temp_nested_array.each do |time, temp|
hour = time.hour + time_offset_in_hours
outdoor_temps << temp if self.send("#{cycle}_time_hours_include?", hour)
end
outdoor_temp_array
end
def get_cycle_metric(cycle, measurement)
array = []
self.send("#{measurement}_nested_array").each do |time, measure|
hour = time.hour + time_offset_in_hours
array << temp if self.send("#{cycle}_time_hours_include?", hour)
end
array
end
end
# def self.included(receiver)
# receiver.extend ClassMethods
# receiver.send :include, InstanceMethods
# end
end
|
# First file to be loaded when the gem is invoked.
# Need to require everything here
# Fetch all the configuration values here
require "koduc_express_paypal/version"
require "koduc_express_paypal/koduc_check_environment"
require "koduc_express_paypal/koduc_request"
require "koduc_express_paypal/koduc_validation"
require "koduc_express_paypal/koduc_response"
require "koduc_exception_handling/koduc_api_errors"
require "koduc_refund/koduc_refund"
require "koduc_refund/koduc_refund_validation"
require "active_support"
require "active_support/core_ext"
require "rest_client"
# Declare a constant api_version
# This is the release version of the developing API used in this gem
# One of the parameters mandatory for each call
# No need to pass it from the user's side
# Keep it here and change it from here
module KsExpressPaypal
mattr_accessor :api_version
self.api_version = '88.0'
# Method to take the paypal credentials
# The credentials must be included in the app
# Merge the VERSION declared in the KsExpressPaypal module
# Value of the VERSION is declared as constant
def self.ks_merchants_details
begin
ks_merchants_details = Rails.configuration.paypal_credentials.merge(VERSION: KsExpressPaypal.api_version)
rescue => exc
if !exc.message.nil?
error = KsExceptionHandling::KsAPIErrors.new(exc.message)
error.ks_error_messages
end
end
end
end |
# encoding: utf-8
#
# © Copyright 2013 Hewlett-Packard Development Company, L.P.
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
module HP
module Cloud
class CLI < Thor
desc "lb:add <name> <algorithm> <protocol> <port>", "Add a load balancer."
long_desc <<-DESC
Add a load balancer with the specified name, algorithm, protocol and port. You must specify a node and may specify a virtual IP id to create a load balancer.
Examples:
hpcloud lb:add loady ROUND_ROBIN HTTP 80 -n '10.1.1.1:80;10.1.1.2:81' -v '123;39393' # Create a new load balancer 'loady'
DESC
method_option :nodes,
:type => :string, :aliases => '-n', :required => true,
:desc => 'Nodes to associate with the load balancer. Semicolon separated list of colon separated IP and port pairs'
method_option :ips,
:type => :string, :aliases => '-v',
:desc => 'Semicolon separated list of of virtual IPs Ids to associate with the load balancer.'
CLI.add_common_options
define_method "lb:add" do |name, algorithm, protocol, port|
cli_command(options) {
lb = Lbs.new.unique(name)
lb.name = name
algorithm = LbAlgorithms.new.get(algorithm).name
lb.algorithm = algorithm
protocol = LbProtocols.new.get(protocol).name
lb.protocol = protocol
lb.port = port
lb.nodes = parse_nodes(options[:nodes])
lb.virtualIps = parse_virtual_ips(options[:ips])
lb.save
@log.display "Created load balancer '#{name}' with id '#{lb.id}'."
}
end
private
def parse_nodes(value)
return [] if value.nil?
ray = []
begin
value.split(';').each{ |x|
hsh = {}
nod = x.split(':')
raise "Error" if nod.length != 2
hsh["address"] = nod[0]
hsh["port"] = nod[1]
ray << hsh
}
rescue
raise HP::Cloud::Exceptions::General.new("Error parsing nodes '#{value}'")
end
ray
end
def parse_virtual_ips(value)
return [] if value.nil?
ray = []
begin
value.split(';').each{ |x|
ray << {"id"=>x}
}
rescue
raise HP::Cloud::Exceptions::General.new("Error parsing virtual IPs '#{value}'")
end
ray
end
end
end
end
|
require 'spec_helper'
describe Haystack::Rack::JSExceptionCatcher do
let(:app) { double(:call => true) }
let(:options) { double }
let(:active) { true }
let(:config_options) { {:enable_frontend_error_catching => true} }
let(:config) { project_fixture_config('production', config_options) }
before do
Haystack.stub(:config => config)
config.stub(:active? => active)
end
describe "#initialize" do
it "should log to the logger" do
expect( Haystack.logger ).to receive(:debug)
.with('Initializing Haystack::Rack::JSExceptionCatcher')
Haystack::Rack::JSExceptionCatcher.new(app, options)
end
end
describe "#call" do
let(:catcher) { Haystack::Rack::JSExceptionCatcher.new(app, options) }
context "when path is not `/haystack_error_catcher`" do
let(:env) { {'PATH_INFO' => '/foo'} }
it "should call the next middleware" do
expect( app ).to receive(:call).with(env)
end
end
context "when path is `/haystack_error_catcher`" do
let(:transaction) { double(:complete! => true) }
let(:env) do
{
'PATH_INFO' => '/haystack_error_catcher',
'rack.input' => double(:read => '{"foo": "bar"}')
}
end
it "should create a JSExceptionTransaction" do
expect( Haystack::JSExceptionTransaction ).to receive(:new)
.with({'foo' => 'bar'})
.and_return(transaction)
expect( transaction ).to receive(:complete!)
end
context "when `frontend_error_catching_path` is different" do
let(:config_options) do
{
:frontend_error_catching_path => '/foo'
}
end
it "should not create a transaction" do
expect( Haystack::JSExceptionTransaction ).to_not receive(:new)
end
it "should call the next middleware" do
expect( app ).to receive(:call).with(env)
end
end
end
after { catcher.call(env) }
end
end
|
class CreateMatches < ActiveRecord::Migration[6.0]
def change
create_table :matches do |t|
t.integer :user_id
t.string :place_id
t.float :place_lat
t.float :place_lng
t.text :place_name
t.boolean :favorite, default: false
t.timestamps
end
end
end
|
require_relative 'middleware_base'
module BME
class BasicAuth < MiddlewareBase
def initialize(app)
$stdout.puts "BME::BasicAuth"
@settings = YAML.load_file('config/config.yml')
@app = app
end
def call(env)
begin
path = env["PATH_INFO"]
$stdout.puts "BME::BasicAuth"
$stdout.puts path
logs_path = "/logs"
path_regex = Regexp.new("^(#{logs_path}$)|^(#{logs_path}(/.*))$")
if path =~ path_regex
if authorized? env
$stdout.puts "BME::BasicAuth authorized"
@app.call(env)
else
$stdout.puts "BME::BasicAuth not authorized"
headers = {'WWW-Authenticate'=>'Basic realm="Restricted Area"'}
response = Rack::Response.new "Unauthorized", 401, headers
response.finish
end
else
@app.call(env)
end
rescue => e
warn "Error in BME::BasicAuth middleware #{e.message} #{get_stacktrace}"
end
end
private
def authorized?(env)
auth_config = @settings['authentication']
@auth = Rack::Auth::Basic::Request.new(env)
if @auth.provided?
end
@auth.provided? && @auth.basic? && @auth.credentials && @auth.credentials == [auth_config['username'], auth_config['password']]
end
end
end
|
# frozen_string_literal: true
require "spec_helper"
describe GraphQL::Schema::RelayClassicMutation do
describe ".input_object_class" do
it "is inherited, with a default" do
custom_input = Class.new(GraphQL::Schema::InputObject)
mutation_base_class = Class.new(GraphQL::Schema::RelayClassicMutation) do
input_object_class(custom_input)
end
mutation_subclass = Class.new(mutation_base_class)
assert_equal GraphQL::Schema::InputObject, GraphQL::Schema::RelayClassicMutation.input_object_class
assert_equal custom_input, mutation_base_class.input_object_class
assert_equal custom_input, mutation_subclass.input_object_class
end
end
describe ".field" do
it "removes inherited field definitions, creating one with the mutation as the owner" do
assert_equal Jazz::RenameEnsemble, Jazz::RenameEnsemble.fields["ensemble"].owner
assert_equal Jazz::RenameEnsemble, Jazz::RenameEnsemble.payload_type.fields["ensemble"].owner
assert_equal Jazz::RenameEnsembleAsBand, Jazz::RenameEnsembleAsBand.fields["ensemble"].owner
assert_equal Jazz::RenameEnsembleAsBand, Jazz::RenameEnsembleAsBand.payload_type.fields["ensemble"].owner
end
end
describe ".input_type" do
it "has a reference to the mutation" do
mutation = Class.new(GraphQL::Schema::RelayClassicMutation) do
graphql_name "Test"
end
assert_equal mutation, mutation.input_type.mutation
end
end
describe ".null" do
it "is inherited as true" do
mutation = Class.new(GraphQL::Schema::RelayClassicMutation) do
graphql_name "Test"
end
assert mutation.null
end
end
describe "input argument" do
it "sets a description for the input argument" do
mutation = Class.new(GraphQL::Schema::RelayClassicMutation) do
graphql_name "SomeMutation"
end
field = GraphQL::Schema::Field.new(name: "blah", resolver_class: mutation)
assert_equal "Parameters for SomeMutation", field.get_argument("input").description
end
end
describe "execution" do
after do
Jazz::Models.reset
end
it "works with no arguments" do
res = Jazz::Schema.execute <<-GRAPHQL
mutation {
addSitar(input: {}) {
instrument {
name
}
}
}
GRAPHQL
assert_equal "Sitar", res["data"]["addSitar"]["instrument"]["name"]
end
it "works with InputObject arguments" do
res = Jazz::Schema.execute <<-GRAPHQL
mutation {
addEnsembleRelay(input: { ensemble: { name: "Miles Davis Quartet" } }) {
ensemble {
name
}
}
}
GRAPHQL
assert_equal "Miles Davis Quartet", res["data"]["addEnsembleRelay"]["ensemble"]["name"]
end
it "supports extras" do
res = Jazz::Schema.execute <<-GRAPHQL
mutation {
hasExtras(input: {}) {
nodeClass
int
}
}
GRAPHQL
assert_equal "GraphQL::Language::Nodes::Field", res["data"]["hasExtras"]["nodeClass"]
assert_nil res["data"]["hasExtras"]["int"]
# Also test with given args
res = Jazz::Schema.execute <<-GRAPHQL
mutation {
hasExtras(input: {int: 5}) {
nodeClass
int
}
}
GRAPHQL
assert_equal "GraphQL::Language::Nodes::Field", res["data"]["hasExtras"]["nodeClass"]
assert_equal 5, res["data"]["hasExtras"]["int"]
end
it "supports field extras" do
res = Jazz::Schema.execute <<-GRAPHQL
mutation {
hasFieldExtras(input: {}) {
lookaheadClass
int
}
}
GRAPHQL
assert_equal "GraphQL::Execution::Lookahead", res["data"]["hasFieldExtras"]["lookaheadClass"]
assert_nil res["data"]["hasFieldExtras"]["int"]
# Also test with given args
res = Jazz::Schema.execute <<-GRAPHQL
mutation {
hasFieldExtras(input: {int: 5}) {
lookaheadClass
int
}
}
GRAPHQL
assert_equal "GraphQL::Execution::Lookahead", res["data"]["hasFieldExtras"]["lookaheadClass"]
assert_equal 5, res["data"]["hasFieldExtras"]["int"]
end
it "can strip out extras" do
ctx = {}
res = Jazz::Schema.execute <<-GRAPHQL, context: ctx
mutation {
hasExtrasStripped(input: {}) {
int
}
}
GRAPHQL
assert_equal true, ctx[:has_lookahead]
assert_equal 51, res["data"]["hasExtrasStripped"]["int"]
end
end
describe "loading multiple application objects" do
let(:query_str) {
<<-GRAPHQL
mutation($ids: [ID!]!) {
upvoteEnsembles(input: {ensembleIds: $ids}) {
ensembles {
id
}
}
}
GRAPHQL
}
it "loads arguments as objects of the given type and strips `_ids` suffix off argument name and appends `s`" do
res = Jazz::Schema.execute(query_str, variables: { ids: ["Ensemble/Robert Glasper Experiment", "Ensemble/Bela Fleck and the Flecktones"]})
assert_equal ["Ensemble/Robert Glasper Experiment", "Ensemble/Bela Fleck and the Flecktones"], res["data"]["upvoteEnsembles"]["ensembles"].map { |e| e["id"] }
end
it "uses the `as:` name when loading" do
as_bands_query_str = query_str.sub("upvoteEnsembles", "upvoteEnsemblesAsBands")
res = Jazz::Schema.execute(as_bands_query_str, variables: { ids: ["Ensemble/Robert Glasper Experiment", "Ensemble/Bela Fleck and the Flecktones"]})
assert_equal ["Ensemble/Robert Glasper Experiment", "Ensemble/Bela Fleck and the Flecktones"], res["data"]["upvoteEnsemblesAsBands"]["ensembles"].map { |e| e["id"] }
end
it "doesn't append `s` to argument names that already end in `s`" do
query = <<-GRAPHQL
mutation($ids: [ID!]!) {
upvoteEnsemblesIds(input: {ensemblesIds: $ids}) {
ensembles {
id
}
}
}
GRAPHQL
res = Jazz::Schema.execute(query, variables: { ids: ["Ensemble/Robert Glasper Experiment", "Ensemble/Bela Fleck and the Flecktones"]})
assert_equal ["Ensemble/Robert Glasper Experiment", "Ensemble/Bela Fleck and the Flecktones"], res["data"]["upvoteEnsemblesIds"]["ensembles"].map { |e| e["id"] }
end
it "returns an error instead when the ID resolves to nil" do
res = Jazz::Schema.execute(query_str, variables: {
ids: ["Ensemble/Nonexistant Name"],
})
assert_nil res["data"].fetch("upvoteEnsembles")
assert_equal ['No object found for `ensembleIds: "Ensemble/Nonexistant Name"`'], res["errors"].map { |e| e["message"] }
end
it "returns an error instead when the ID resolves to an object of the wrong type" do
res = Jazz::Schema.execute(query_str, variables: {
ids: ["Instrument/Organ"],
})
assert_nil res["data"].fetch("upvoteEnsembles")
assert_equal ["No object found for `ensembleIds: \"Instrument/Organ\"`"], res["errors"].map { |e| e["message"] }
end
it "raises an authorization error when the type's auth fails" do
res = Jazz::Schema.execute(query_str, variables: {
ids: ["Ensemble/Spinal Tap"],
})
assert_nil res["data"].fetch("upvoteEnsembles")
# Failed silently
refute res.key?("errors")
end
end
describe "loading application objects" do
let(:query_str) {
<<-GRAPHQL
mutation($id: ID!, $newName: String!) {
renameEnsemble(input: {ensembleId: $id, newName: $newName}) {
__typename
ensemble {
__typename
name
}
}
}
GRAPHQL
}
it "loads arguments as objects of the given type" do
res = Jazz::Schema.execute(query_str, variables: { id: "Ensemble/Robert Glasper Experiment", newName: "August Greene"})
assert_equal "August Greene", res["data"]["renameEnsemble"]["ensemble"]["name"]
end
it "loads arguments as objects when provided an interface type" do
query = <<-GRAPHQL
mutation($id: ID!, $newName: String!) {
renameNamedEntity(input: {namedEntityId: $id, newName: $newName}) {
namedEntity {
__typename
name
}
}
}
GRAPHQL
res = Jazz::Schema.execute(query, variables: { id: "Ensemble/Robert Glasper Experiment", newName: "August Greene"})
assert_equal "August Greene", res["data"]["renameNamedEntity"]["namedEntity"]["name"]
assert_equal "Ensemble", res["data"]["renameNamedEntity"]["namedEntity"]["__typename"]
end
it "loads arguments as objects when provided an union type" do
query = <<-GRAPHQL
mutation($id: ID!, $newName: String!) {
renamePerformingAct(input: {performingActId: $id, newName: $newName}) {
performingAct {
__typename
... on Ensemble {
name
}
}
}
}
GRAPHQL
res = Jazz::Schema.execute(query, variables: { id: "Ensemble/Robert Glasper Experiment", newName: "August Greene"})
assert_equal "August Greene", res["data"]["renamePerformingAct"]["performingAct"]["name"]
assert_equal "Ensemble", res["data"]["renamePerformingAct"]["performingAct"]["__typename"]
end
it "uses the `as:` name when loading" do
band_query_str = query_str.sub("renameEnsemble", "renameEnsembleAsBand")
res = Jazz::Schema.execute(band_query_str, variables: { id: "Ensemble/Robert Glasper Experiment", newName: "August Greene"})
assert_equal "August Greene", res["data"]["renameEnsembleAsBand"]["ensemble"]["name"]
end
it "returns an error instead when the ID resolves to nil" do
res = Jazz::Schema.execute(query_str, variables: {
id: "Ensemble/Nonexistant Name",
newName: "August Greene"
})
assert_nil res["data"].fetch("renameEnsemble")
assert_equal ['No object found for `ensembleId: "Ensemble/Nonexistant Name"`'], res["errors"].map { |e| e["message"] }
end
it "returns an error instead when the ID resolves to an object of the wrong type" do
res = Jazz::Schema.execute(query_str, variables: {
id: "Instrument/Organ",
newName: "August Greene"
})
assert_nil res["data"].fetch("renameEnsemble")
assert_equal ["No object found for `ensembleId: \"Instrument/Organ\"`"], res["errors"].map { |e| e["message"] }
end
it "raises an authorization error when the type's auth fails" do
res = Jazz::Schema.execute(query_str, variables: {
id: "Ensemble/Spinal Tap",
newName: "August Greene"
})
assert_nil res["data"].fetch("renameEnsemble")
# Failed silently
refute res.key?("errors")
end
end
describe "migrated legacy tests" do
describe "specifying return interfaces" do
class MutationInterfaceSchema < GraphQL::Schema
module ResultInterface
include GraphQL::Schema::Interface
field :success, Boolean, null: false
field :notice, String
end
module ErrorInterface
include GraphQL::Schema::Interface
field :error, String
end
class BaseReturnType < GraphQL::Schema::Object
implements ResultInterface, ErrorInterface
end
class ReturnTypeWithInterfaceTest < GraphQL::Schema::RelayClassicMutation
object_class BaseReturnType
field :name, String
def resolve
{
name: "Type Specific Field",
success: true,
notice: "Success Interface Field",
error: "Error Interface Field"
}
end
end
class Mutation < GraphQL::Schema::Object
field :custom, mutation: ReturnTypeWithInterfaceTest
end
mutation(Mutation)
def self.resolve_type(abs_type, obj, ctx)
NO_OP_RESOLVE_TYPE.call(abs_type, obj, ctx)
end
end
it 'makes the mutation type implement the interfaces' do
mutation = MutationInterfaceSchema::ReturnTypeWithInterfaceTest
expected_interfaces = [MutationInterfaceSchema::ResultInterface, MutationInterfaceSchema::ErrorInterface]
actual_interfaces = mutation.payload_type.interfaces
assert_equal(expected_interfaces, actual_interfaces)
end
it "returns interface values and specific ones" do
result = MutationInterfaceSchema.execute('mutation { custom(input: {clientMutationId: "123"}) { name, success, notice, error, clientMutationId } }')
assert_equal "Type Specific Field", result["data"]["custom"]["name"]
assert_equal "Success Interface Field", result["data"]["custom"]["notice"]
assert_equal true, result["data"]["custom"]["success"]
assert_equal "Error Interface Field", result["data"]["custom"]["error"]
assert_equal "123", result["data"]["custom"]["clientMutationId"]
end
end
if testing_rails?
describe "star wars mutation tests" do
let(:query_string) {%|
mutation addBagel($clientMutationId: String, $shipName: String = "Bagel") {
introduceShip(input: {shipName: $shipName, factionId: "1", clientMutationId: $clientMutationId}) {
clientMutationId
shipEdge {
node { name, id }
}
faction { name }
}
}
|}
let(:introspect) {%|
{
__schema {
types { name, fields { name } }
}
}
|}
after do
StarWars::DATA["Ship"].delete("9")
StarWars::DATA["Faction"]["1"].ships.delete("9")
end
it "supports null values" do
result = star_wars_query(query_string, { "clientMutationId" => "1234", "shipName" => nil })
expected = {"data" => {
"introduceShip" => {
"clientMutationId" => "1234",
"shipEdge" => {
"node" => {
"name" => nil,
"id" => GraphQL::Schema::UniqueWithinType.encode("Ship", "9"),
},
},
"faction" => {"name" => StarWars::DATA["Faction"]["1"].name }
}
}}
assert_equal(expected, result)
end
it "supports lazy resolution" do
result = star_wars_query(query_string, { "clientMutationId" => "1234", "shipName" => "Slave II" })
assert_equal "Slave II", result["data"]["introduceShip"]["shipEdge"]["node"]["name"]
end
it "returns the result & clientMutationId" do
result = star_wars_query(query_string, { "clientMutationId" => "1234" })
expected = {"data" => {
"introduceShip" => {
"clientMutationId" => "1234",
"shipEdge" => {
"node" => {
"name" => "Bagel",
"id" => GraphQL::Schema::UniqueWithinType.encode("Ship", "9"),
},
},
"faction" => {"name" => StarWars::DATA["Faction"]["1"].name }
}
}}
assert_equal(expected, result)
end
it "doesn't require a clientMutationId to perform mutations" do
result = star_wars_query(query_string)
new_ship_name = result["data"]["introduceShip"]["shipEdge"]["node"]["name"]
assert_equal("Bagel", new_ship_name)
end
describe "return_field ... property:" do
it "resolves correctly" do
query_str = <<-GRAPHQL
mutation {
introduceShip(input: {shipName: "Bagel", factionId: "1"}) {
aliasedFaction { name }
}
}
GRAPHQL
result = star_wars_query(query_str)
faction_name = result["data"]["introduceShip"]["aliasedFaction"]["name"]
assert_equal("Alliance to Restore the Republic", faction_name)
end
end
describe "handling errors" do
it "supports returning an error in resolve" do
result = star_wars_query(query_string, { "clientMutationId" => "5678", "shipName" => "Millennium Falcon" })
expected = {
"data" => {
"introduceShip" => nil,
},
"errors" => [
{
"message" => "Sorry, Millennium Falcon ship is reserved",
"locations" => [ { "line" => 3 , "column" => 13}],
"path" => ["introduceShip"]
}
]
}
assert_equal(expected, result)
end
it "supports raising an error in a lazy callback" do
result = star_wars_query(query_string, { "clientMutationId" => "5678", "shipName" => "Ebon Hawk" })
expected = {
"data" => {
"introduceShip" => nil,
},
"errors" => [
{
"message" => "💥",
"locations" => [ { "line" => 3 , "column" => 13}],
"path" => ["introduceShip"]
}
]
}
assert_equal(expected, result)
end
it "supports raising an error in the resolve function" do
result = star_wars_query(query_string, { "clientMutationId" => "5678", "shipName" => "Leviathan" })
expected = {
"data" => {
"introduceShip" => nil,
},
"errors" => [
{
"message" => "🔥",
"locations" => [ { "line" => 3 , "column" => 13}],
"path" => ["introduceShip"]
}
]
}
assert_equal(expected, result)
end
end
end
end
end
describe "authorizing arguments from superclasses" do
class RelayClassicArgumentAuthSchema < GraphQL::Schema
class BaseArgument < GraphQL::Schema::Argument
def authorized?(_object, args, context)
authed_val = context[:authorized_value] ||= Hash.new { |h,k| h[k] = {} }
if (prev_val = authed_val[context[:current_path]][self.path])
raise "Duplicate `#authorized?` call on #{self.path} @ #{context[:current_path]} (was: #{prev_val.inspect}, is: #{args.inspect})"
end
authed_val[context[:current_path]][self.path] = args
authed = context[:authorized] ||= {}
authed[context[:current_path]] = super
end
end
class NameInput < GraphQL::Schema::InputObject
argument_class BaseArgument
argument :name, String
end
class NameOne < GraphQL::Schema::RelayClassicMutation
argument_class BaseArgument
argument :name, String, as: :name_one
field :name, String
def resolve(**arguments)
{
name: arguments[:name_one]
}
end
end
class NameTwo < GraphQL::Schema::RelayClassicMutation
input_type NameInput
field :name, String
def resolve(**arguments)
{
name: arguments[:name]
}
end
end
class NameThree < GraphQL::Schema::RelayClassicMutation
input_object_class NameInput
field :name, String
def resolve(**arguments)
{
name: arguments[:name]
}
end
end
class Thing < GraphQL::Schema::Object
field :name, String
end
class NameFour < GraphQL::Schema::RelayClassicMutation
argument_class BaseArgument
argument :thing_id, ID, loads: Thing
field :thing, Thing
def resolve(**arguments)
{
thing: arguments[:thing]
}
end
end
class Mutation < GraphQL::Schema::Object
field :name_one, mutation: NameOne
field :name_two, mutation: NameTwo
field :name_three, mutation: NameThree
field :name_four, mutation: NameFour
end
mutation(Mutation)
def self.object_from_id(id, ctx)
{ name: id }
end
def self.resolve_type(abs_type, obj, ctx)
Thing
end
end
it "calls #authorized? on arguments defined on the mutation" do
res = RelayClassicArgumentAuthSchema.execute("mutation { nameOne(input: { name: \"Camry\" }) { name } }")
assert_equal true, res.context[:authorized][["nameOne"]]
end
it "calls #authorized? on arguments defined on the input_type" do
res = RelayClassicArgumentAuthSchema.execute("mutation { nameTwo(input: { name: \"Camry\" }) { name } }")
assert_equal true, res.context[:authorized][["nameTwo"]]
end
it "calls #authorized? on arguments defined on the inputObjectClass" do
res = RelayClassicArgumentAuthSchema.execute("mutation { nameThree(input: { name: \"Camry\" }) { name } }")
assert_equal true, res.context[:authorized][["nameThree"]]
end
it "calls #authorized? on loaded argument values" do
res = RelayClassicArgumentAuthSchema.execute("mutation { nameFour(input: { thingId: \"Corolla\" }) { thing { name } } }")
assert_equal true, res.context[:authorized][["nameFour"]]
assert_equal({ name: "Corolla"}, res.context[:authorized_value][["nameFour"]]["NameFour.thingId"])
assert_equal "Corolla", res["data"]["nameFour"]["thing"]["name"]
end
end
end
|
require_relative 'find_by'
require_relative 'errors'
require 'csv'
class Udacidata
@@data_path = File.dirname(__FILE__)+"/../data/data.csv"
# adds new records
def self.create(attributes={})
new_item = self.new(attributes)
CSV.open(@@data_path, "a+") do |csv|
csv << [new_item.id, new_item.brand, new_item.name, new_item.price]
end
new_item
end
# pushes all record to all_products
def self.all
all_products = []
CSV.foreach(@@data_path, headers: true) do |row|
all_products << self.new(id: row[0], brand: row[1], name: row[2], price: row[3])
end
all_products
end
# product not found errror
def self.product_not_found(item)
raise ProductNotFoundErrors, "Error : '#{item}' does not Exist"
end
#returns first record or first few requred numbers of records
def self.take_items(from, n=nil)
n ? all.send(from, n) : all.public_send(from)
end
def self.first(n=nil)
take_items(:first, n)
end
def self.last(n=nil)
take_items(:last, n)
end
# finds record with id
def self.find(item)
found_item = all.find { |e| e.id == item}
found_item == nil ? product_not_found(item) : found_item
end
#opens csv file
def self.open_data
CSV.table(@@data_path)
end
#updates csv file with given records
def self.update_date(all_items)
File.open(@@data_path, 'w+') do |f|
f.write(all_items.to_csv)
end
end
#delete record with id
def self.found_item_delete(id)
all_items = open_data
all_items.delete_if do |row|
row[:id] == id
end
update_date(all_items)
end
# destroyes record
def self.destroy(item)
to_be_deleted = find(item)
to_be_deleted ? found_item_delete(to_be_deleted.id) : product_not_found(to_be_deleted.id)
to_be_deleted
end
# finds records with brand or name
def self.where(val)
items = all.select! { |item| item.send(val.keys.first) == val.values.first}
return items
end
# updates records with given values
def update(options={})
item = self.class.find(@id)
item.brand.replace(options[:brand]) if options[:brand]
item.name.replace(options[:name])if options[:name]
item.price.replace(options[:price].to_s) if options[:price]
self.class.destroy(@id)
self.class.create(id: @id, brand: item.brand, name: item.name, price: item.price.to_f)
end
end
|
require 'spec_helper'
describe Bumpy do
describe ".bump_version" do
def bump(v)
subject.bump_version(v)
end
TEST_DATA = [
['1.0.0', '1.0.1'],
['1.0.9', '1.0.10'],
['1.0.5.pre9', '1.0.5.pre10'],
['12.0', '12.1'],
['1.2.3.dev.9', '1.2.3.dev.10']
]
TEST_DATA.each do |from, to|
it "correctly bumps #{from} to #{to}" do
bump(from).should == to
end
end
end
end
|
class AddCouncilIdToProperty < ActiveRecord::Migration
def change
add_column :properties, :council_id, :integer
end
end
|
require "digest"
class User < ActiveRecord::Base
attr_accessor :password
attr_accessible :name, :email, :password, :password_confirmation
#Microposts association
has_many :microposts, :dependent => :destroy
#users who he follows
has_many :relationships, :foreign_key => "follower_id", :dependent => :destroy
has_many :following, :through => :relationships, :source => :followed
#users who follow him
has_many :reverse_relationships, :foreign_key => "followed_id", :class_name => "Relationship", :dependent => :destroy
has_many :followers, :through => :reverse_relationships, :source => :follower
#Validations
EmailRegex = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i
validates_presence_of :name, :email
validates_length_of :name, :maximum => 50
validates_format_of :email, :with => EmailRegex
validates_uniqueness_of :email, :case_sensitive => false
#Automatically create a virtual attribute passoword:confirmation
validates_confirmation_of :password
#Password validation
validates_presence_of :password
validates_length_of :password, :within => 6..40
before_save :encrypt_password
#check whether the entered password matches the password in the record
def has_password?(submitted_password)
#compare encrypted password with the encrypted version of the submitted_password
encrypted_password == encrypt(submitted_password)
end
def self.authenticate(email, submitted_password)
user = User.find_by_email email
return nil if user.nil?
return user if user.has_password? submitted_password
end
#for sessions
def remember_me!
self.remember_token = encrypt "#{salt}--#{id}--#{Time.now.utc}"
save_without_validation
end
#tweets feed
def feed
Micropost.from_users_followed_by(self)
end
def follow!(followed)
relationships.create!(:followed_id => followed.id)
end
def following?(followed)
relationships.find_by_followed_id(followed)
end
def unfollow!(followed)
relationships.find_by_followed_id(followed).destroy
end
private
def encrypt_password
unless password.nil?
self.salt = make_salt
self.encrypted_password = encrypt self.password
end
end
def encrypt(string)
secure_hash "#{salt}#{string}"
end
def make_salt
secure_hash "#{Time.now.utc}#{password}"
end
def secure_hash(string)
Digest::SHA2.hexdigest string
end
end
|
require 'spec_helper'
describe Author do
let(:invalid_names) {['', nil, '12ab34', 'ab12cd']}
let(:invalid_emails) {['blah.com', '@blah.com', '@@.com', 'blah@.com', 'blah', '@@blah.com', 'com', '.com']}
it {should have_valid(:first_name).when('Austin')}
it {should_not have_valid(:first_name).when(*invalid_names)}
it {should have_valid(:last_name).when('Winslow')}
it {should_not have_valid(:last_name).when(*invalid_names)}
it {should have_valid(:email).when('blah@blah.com')}
it {should_not have_valid(:email).when(*invalid_emails)}
it 'should be unique' do
author1 = FactoryGirl.build(:author)
author2 = FactoryGirl.build(:author)
expect(author1.save).to be_true
expect(author2.save).to be_false
end
it {should have_many :entries}
it {should have_many :comments}
end
|
require "alimento/version"
require "alimento/lista"
require "alimento/IG_fun"
require "alimento/ordenar"
require "benchmark"
module Alimento
class Alimento
attr_reader :nombre, :prt, :gluc, :lip
include Comparable
def <=>(another)
kcal <=> another.kcal
end
def initialize(nombre,prt,gluc,lip)
@nombre=nombre
@prt=prt
@gluc=gluc
@lip=lip
end
def to_s()
"#{@nombre} prt=#{@prt}g gluc=#{@gluc}g lip=#{@lip}g"
end
def kcal()
@prt*4+@gluc*4+@lip*9
end
end
class Grupoal < Alimento
def initialize(grupo,nombre,prt,gluc,lip)
super(nombre,prt,gluc,lip)
@grupo=grupo
end
def to_s
puts @grupo+"\n\t"+super.to_s
end
end
class Plato
@@talimentos=[
Alimento.new("Huevo", 14.1, 0.0, 19.5),
Alimento.new("Leche", 3.3, 4.8, 3.2),
Alimento.new("Mantequilla" , 0.7, 0.0, 83.2),
Alimento.new("Yogurt", 3.8, 4.9, 3.8),
Alimento.new("Cerdo", 21.5, 0.0, 6.3),
Alimento.new("Ternera", 21.1, 0.0, 3.1),
Alimento.new("Pollo", 20.6, 0.0, 5.6),
Alimento.new("Bacalao", 17.7, 0.0, 0.4),
Alimento.new("Atun", 21.5, 0.0, 15.5),
Alimento.new("Salmon", 19.9, 0.0, 13.6),
Alimento.new("Aceite de oliva", 0.0, 0.2, 99.6),
Alimento.new("Chocolate", 5.3, 47.0, 30.0),
Alimento.new("Azucar", 0.0, 99.8, 0.0),
Alimento.new("Arroz", 6.8, 77.7, 0.6),
Alimento.new("Lentejas", 23.5, 52.0, 1.4),
Alimento.new("Papas", 2.0, 15.4, 0.1),
Alimento.new("Tomate", 1.0, 3.5, 0.2),
Alimento.new("Cebolla", 1.3, 5.8, 0.3),
Alimento.new("Calabaza", 1.1, 4.8, 0.1),
Alimento.new("Manzana", 0.3, 12.4, 0.4),
Alimento.new("Platano", 1.2, 21.4, 0.2),
Alimento.new("Pera", 0.5, 12.7, 0.3)
]
@@tmediciones=[
["pieza",40],
["taza",30],
["cucharon",10],
["cucharada",5],
["pizca",2],
["cucharilla",3]
]
def initialize(nombre, &bloque)
@nombre=nombre
@alimentos=[]
@kcal=0
if block_given?
if bloque.arity == 1
yield self
else
instance_eval(&bloque)
end
end
end
def to_s
output = @nombre
output << "\n#{'=' * @nombre.size}\nComposición nutricional:\n"
@alimentos.each do |alimento|
output << alimento[0].to_s << " kcal=#{alimento[1]}\n"
end
output << "Valor energético total: #{@kcal}\n"
end
def vegetal(nombre, cantidad={})
aux=[]
@@talimentos.each do |alimento|
if nombre==alimento.nombre
aux << alimento
aux << alimento.kcal*cantidad[:gramos] if cantidad[:gramos]
if cantidad[:porcion]
@@tmediciones.each do |unidad|
porc=cantidad[:porcion].each_line(" ").to_a
aux << aux[0].kcal*unidad[1]*porc[0].to_f if unidad[0]=porc[1]
end
end
@alimentos << aux
@kcal+=aux[1]
end
end
end
#def fruta end
#def cereal end
#def proteina end
#def aceite end
#def agua end
end
end
|
require 'spec_helper'
describe 'nfs::server::stunnel' do
on_supported_os.each do |os, facts|
context "on #{os}" do
let(:pre_condition) { 'class { "nfs": is_server => true }' }
let(:facts) { facts }
it { is_expected.to compile.with_all_deps }
it { is_expected.to contain_class('nfs::server') }
it { is_expected.to create_class('nfs::server::stunnel') }
if facts[:os][:release][:major] == '7'
it { is_expected.to create_stunnel__instance('nfs').with_systemd_wantedby([
'rpc-statd.service',
'nfs-mountd.service',
'nfs-rquotad.service',
'nfs-server.service',
'rpcbind.socket',
'nfs-idmapd.service',
'rpc-gssd.service',
'gssproxy.service',
] ) }
end
end
end
end
|
require 'optparse'
module NamecheapZoneImporter
# Parse command line arguments into a zone.
class FromCommandLine
def self.parse!(argv)
options = {}
OptionParser.new do |opts|
opts.banner = "Usage: #{$PROGRAM_NAME} -f [zone file] -u [namecheap username] -k [namecheap api key]"
opts.on('-f', '--zonefile MANDATORY', 'Zonefile') do |value|
options[:zonefile] = value
end
opts.on('-u', '--username MANDATORY', 'Namecheap Username') do |value|
options[:username] = value
end
opts.on('-k', '--apikey MANDATORY', 'Namecheap API Key') do |value|
options[:apikey] = value
end
opts.on('-h', '--help') do |value|
puts opts
exit
end
end.parse!(argv)
options
end
end
end
|
class AddMembershipIdToClients < ActiveRecord::Migration
def change
add_reference :clients, :membership, index: true, foreign_key: true
end
end
|
require 'promotions_parser'
RSpec.describe PromotionsParser do
let(:promotion_parser) { described_class.new promo_rules_json }
describe '#value_rules' do
subject { promotion_parser.value_rules.first }
it 'returns value rules from promotions' do
expect(subject).to have_key(:minimum_value)
expect(subject).to have_key(:discount_decimal)
end
end
describe '#volume_rules' do
let(:product_code) { "001".to_sym }
subject { promotion_parser.volume_rules }
it { expect(subject).to have_key(product_code)}
it { expect(subject[product_code]).to have_key :minimum_volume_required }
it { expect(subject[product_code]).to have_key :discounted_price }
end
end |
# 1. print the menu and ask the user what to do
# 2. read the input and save it into a variable
# 3. do what the user has asked
# 4. repeat from step 1
@students = []#this @students[] is now global and accessible to all methods
def interactive_menu
loop do
print_menu
process(gets.chomp)#can send the selection a variable.
end
end
def print_menu
puts "1. Input Students"
puts "2. Show the Students"
puts "9. Exit"
end
def show_students
print_header
puts @students
print_student_list
print_footer
end
def process(selection)
case selection
when "1"
input_students
when "2"
show_students
when "9"
exit#this will exit the program
else
puts "I don't know what you mean try again"
end
end
def print_header
puts "The students of my cohort at Makers Academy".center(50)
puts "-------------------------".center(50)
end
def print_student_list
if @students.length > 0
countlist = @students.dup#without countlist just refs students and the shift will actually change students. Use 'dup' to make a copy of students and assign it to 'countlist'. Ruby passed by reference
until countlist.length == 0 do
student = countlist.shift
if student[:name].length < 12
puts "Name: #{student[:name]} (#{student[:cohort]} cohort) Hobbies: #{student[:hobbies]} COB: #{student[:COB]} Height: #{student[:height]}".center(50) #using a hash makes it better understood what we are doing.
end
end
else
puts "No students entered".center(50)
end
end
def print_footer
#finally, we print the total
puts "=======================".center(50)
puts "Overall we have #{@students.length} great student#{@plural}".center(50)
end
def input_students
puts "Please enter the names of the students"
puts "To finish, just hit the return key twice"
keyArray = [:hobbies, :COB,:height]
loop do #loop while the name is not empty repeat this code http://blade.nagaokaut.ac.jp/cgi-bin/scat.rb/ruby/ruby-core/6745
#get user details
temp = Hash.new#used to capture the each student
puts 'Enter first name and then the cohort: '
name, cohort = gets.split.map{|i| i.to_sym} #split will break the text up into an array and each element will go to each variable. Split defaults on whitespace. map { |i| i.to_s } same as map(&:to_s)
break if name.nil? #condition to exit the loop
temp[:name] = name
if cohort.nil?
temp[:cohort] = 'n/a'
else temp[:cohort] = cohort#default value for cohort if empty
end
keyArray.each do |key|#enter in the remaining attributes and sets a default value
puts "Enter #{key}:"
val = gets.gsub(/\n/,'').to_sym
val = 'n/a' if val.empty?
temp[key] = val
end
puts "Press Enter to add student #{name} else type 'DEL' to remove"
update = gets.gsub(/\n/,'').downcase
next if update == 'del'#restart the loop and discard the last student
#add the student has to the array
@students << temp
@plural = pluralize(@students)
puts "now we have #{@students.length} student#{@plural}".center(50)
puts "============================".center(50)
end
#returns the array of students and groups them by cohort.
return @students.group_by{|key| key[:cohort]}.values.flatten#had to flatten as it puts it an array when returned.
end
#will check the student count and return a 's' to pluralize the word with an s
def pluralize student_list
if student_list.length > 1
return 's'
else ''
end
end
interactive_menu
|
class PicturesController < AuthenticatedController
def new
if current_user.galleries.length == 0
@gallery = current_user.galleries.build(:title => I18n.t('pictures.default_gallery'))
else
@gallery = current_user.galleries.first
end
@picture = @gallery.pictures.build
end
def create
@picture = Picture.new(params[:picture])
@post = @picture.post
@post.user = current_user
respond_to do |format|
if @picture.save
format.js { render 'posts/create' }
format.html { redirect_to request.referer, :notice => I18n.t('pictures.posted') }
else
format.js { render 'new' }
format.html { redirect_to request.referer, :error => I18n.t('pictures.post_failed')}
end
end
end
def update
@picture = Picture.find(params[:id])
respond_to do |format|
if @picture.update_attributes(params[:picture])
@post = @picture.post
format.js { render 'posts/create' }
format.html { redirect_to root_path, :notice => I18n.t('pictures.posted') }
else
format.js { render 'edit' }
format.html { redirect_to root_path, :error => I18n.t('pictures.post_failed')}
end
end
end
# list galleries
def index
@galleries = current_user.galleries
render :layout => 'home'
end
# show gallery
def show
@picture = Picture.find(params[:id])
@gallery = @picture.gallery
@index = @gallery.pictures.index(@picture)
end
# delete a picture
def destroy
end
end
|
require 'aws-sdk'
require 'yaml'
require 'hashie'
module SportNginAwsAuditor
class AwsConfig < Hash
include Hashie::Extensions::IndifferentAccess
end
class AWSSDK
def self.authenticate(environment)
shared_credentials = Aws::SharedCredentials.new(profile_name: environment)
Aws.config.update({region: 'us-east-1', credentials: shared_credentials})
iam = Aws::IAM::Client.new
# this will be an array of 0 or 1 because iam.list_mfa_devices.mfa_devices will only return 0 or 1 device per user;
# if user doesn't have MFA enabled, then this loop won't even execute
iam.list_mfa_devices.mfa_devices.each do |mfadevice|
mfa_serial_number = mfadevice.serial_number
mfa_token = Output.ask("Enter MFA token: "){ |q| q.validate = /^\d{6}$/ }
session_credentials_hash = get_session(mfa_token,
mfa_serial_number,
shared_credentials.credentials.access_key_id,
shared_credentials.credentials.secret_access_key).credentials
session_credentials = Aws::Credentials.new(session_credentials_hash.access_key_id,
session_credentials_hash.secret_access_key,
session_credentials_hash.session_token)
Aws.config.update({region: 'us-east-1', credentials: session_credentials})
end
end
def self.get_session(mfa_token, mfa_serial_number, access_key_id, secret_access_key)
return @session if @session
sts = Aws::STS::Client.new(access_key_id: access_key_id,
secret_access_key: secret_access_key,
region: 'us-east-1')
@session = sts.get_session_token(duration_seconds: 3600,
serial_number: mfa_serial_number,
token_code: mfa_token)
end
def self.authenticate_with_roles(environment)
Aws.config.update({region: 'us-east-1'})
end
end
end
|
class CreatePouches < ActiveRecord::Migration[5.1]
def change
create_table :pouches do |t|
t.string :name
t.string :rarity
t.string :category
t.string :location
t.string :duration
t.string :first_effect, array: true
t.string :second_effect, array: true
t.string :third_effect, array: true
t.string :shop
t.timestamps
end
end
end
|
class FontRokkitt < Formula
head "https://github.com/google/fonts.git", verified: "github.com/google/fonts", branch: "main", only_path: "ofl/rokkitt"
desc "Rokkitt"
desc "Slab Serif font family"
homepage "https://fonts.google.com/specimen/Rokkitt"
def install
(share/"fonts").install "Rokkitt-Italic[wght].ttf"
(share/"fonts").install "Rokkitt[wght].ttf"
end
test do
end
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.