text stringlengths 10 2.61M |
|---|
# Load the rails application
require File.expand_path('../application', __FILE__)
###################################
####### THEMEABLE OVERRIDES #######
###################################
TEST_DATA = false
DEFAULT_PER_PAGE = 20
SUPPORT_EMAIL = "info@localcycle.org"
IMAGE_STYLES = {large: "600x400>", medium: "240x160>", thumb: "60x40>"}
DEFAULT_PAPERCLIP_IMAGE = "/images/:style/missing.png"
###################################
## DISPLAY
GENDER = {
"Male" => "male",
"Female" => "female"
}
ROLES = {
"admin" => "Admin",
"market_manager" => "Market Manager",
"buyer" => "Buyer",
"producer" => "Producer"
}
REGISTERABLE_ROLES = {
"market_manager" => "Market Manager",
"buyer" => "Buyer",
"producer" => "Producer"
}
SIZES = {
0 => "Small",
1 => "Medium",
2 => "Large"
}
ACREAGE = {
0 => "Small: 0-10",
1 => "Medium: 10-50",
2 => "Large: 50+"
}
DISTANCES = {
20 => "20 miles",
50 => "50 miles",
100 => "100 miles",
250 => "250 miles"
}
FREQUENCIES = {
"daily" => "Daily",
"weekly" => "Weekly",
"monthly" => "Monthly"
}
WEEKDAYS = {
1 => "Mon",
2 => "Tues",
3 => "Wed",
4 => "Thurs",
5 => "Fri",
6 => "Sat",
7 => "Sun",
}
NORMAL_HOURS = {
# 1 => "1am",
# 2 => "2am",
# 3 => "3am",
# 4 => "4am",
# 5 => "5am",
# 6 => "6am",
# 7 => "7am",
8 => "8am",
9 => "9am",
10 => "10am",
11 => "11am",
12 => "Noon",
13 => "1pm",
14 => "2pm",
15 => "3pm",
16 => "4pm",
17 => "5pm",
18 => "6pm",
# 19 => "7pm",
# 20 => "8pm",
# 21 => "9pm",
# 22 => "10pm",
# 23 => "11pm",
# 0 => "Midnight",
}
GROWING_METHODS = {
0 => "Custom",
1 => "Responsible",
2 => "Green",
3 => "Organic",
4 => "Biodynamic"
}
GROWING_METHODS_TEXT = {
0 => 'Custom',
1 => '<strong style="color: #8bc63e;">Responsible</strong> Farms have a reverence for the ecological and social wellbeing of local communities. Many employ conventional farming methods, but go a step beyond industrial agriculture.</label>
<ul>
<li>All produce farms must utilize Integrated Pest Management and crop rotation at a minimum, and be GMO-free.</li>
<li>All livestock farmers must not be CAFOs, must treat animals humanely, must raise animals that are hormone-free, and must avoid the use of antibiotics.</li>
<li>All mid to large sized farms on LocalCycle must employ worker safety systems to ensure quality of work life for all employees.</li>
</ul>
<small>If your farm goes beyond these basic requirements but is not certified organic, see <em>Green</em> label.</small>',
2 => '<strong style="color: #60ac37;">Green</strong> farms go beyond <em>Responsible</em>, additionally meeting several requirements of organic farming without being organic certified. Green Farms do not employ synthetic pesticides nor chemical fertilizers.',
3 => '<strong style="color: #39b54a;">Organic (certified)</strong> food is produced without antibiotics, growth hormones, conventional pesticides, petroleum-based fertilizers or sewage sludge-based fertilizers, bioengineering, or ionizing radiation. U.S. Department of Agriculture (USDA) certification is required before a product can be labeled "organic."',
4 => '<strong style="color: #146527;">Biodynamic (certified)</strong> agriculture considers both the material and spiritual context of food production and works with terrestrial as well as cosmic influences. The influence of planetary rhythms on the growth of plants and animals, in terms of the ripening power of light and warmth, is managed by guiding cultivation times with an astronomical calendar. All organic principles apply to biodynamic farming.'
}
AGREEMENT_TYPES = {
"onetime" => "One Time",
"seasonal" => "Seasonal",
"indefinite" => "Indefinite",
}
UNIT_TYPE = {
"lb" => "Pound",
"oz" => "Ounce",
# "3lb" => "3 Pounds",
# "5lb" => "5 Pounds",
# "10lb" => "10 Pounds",
# "15lb" => "15 Pounds",
# "20lb" => "20 Pounds",
# "25lb" => "25 Pounds",
"bunch" => "Bunch",
"bu" => "Bushel",
"1/2bu" => "Half Bushel",
"4/5bu" => "4/5 Bushel",
"case" => "Case",
"doz" => "Dozen",
"ea" => "Single",
"flat" => "Flat",
"gal" => "Gallon",
"1/2gal" => "Half Gallon",
"pack" => "Pack",
"piece" => "Piece",
"pt" => "Pint",
"1/2pt" => "Half Pint",
"wheel" => "Wheel",
"1/2wheel" => "Half Wheel",
"1/4wheel" => "Quarter Wheel"
}
###################################
###################################
## MODULE
###################################
###################################
## EMAIL
ADDITIONAL_ADMINS = ["Macklin Chaffee <macklin@goldenorbventure.com>"]
REPLY_TO_ADDRESS = ["LocalCycle Support <info@localcycle.org>"]
###################################
# Initialize the rails application
LOCALCYCLE::Application.initialize!
|
class AddSegmentsStatus < ActiveRecord::Migration
def self.up
add_column :segments, :reviewer_id, :integer
add_column :segments, :translator_id, :integer
add_column :segments, :status_id, :string
end
def self.down
remove_column :segments, :reviewer_id
remove_column :segments, :translator_id
remove_column :segments, :status_id
end
end
|
require 'mechanize'
require 'json'
require 'singleton'
require 'faker'
require 'logger'
require_relative 'app/ebay_api'
require_relative 'app/IP'
require_relative 'app/account'
require_relative 'app/user'
class EbatEbay
include Singleton
def initialize
@IP_list = JSON.parse(File.read(File.expand_path('../../db/ip', __FILE__)))
@CONFIG_list = JSON.parse(File.read(File.expand_path('../../db/configs', __FILE__)))
@EMAIL_list = JSON.parse(File.read(File.expand_path('../../db/email', __FILE__)))
end
def run
retrieve_IP
@account = EbayAPI.sign_up(generate_user)
puts "Finished: #{@account.to_h}"
save
end
protected
def save
@EMAIL_list.delete(@email)
@IP_list.push(@ip.ip)
File.open(File.expand_path('../../db/ip', __FILE__), 'w') do |f|
f.write(@IP_list.to_json)
end
File.open(File.expand_path('../../db/email', __FILE__), 'w') do |f|
f.write(@EMAIL_list.to_json)
end
accounts = JSON.parse(File.read((File.expand_path('../../db/ebay_accounts', __FILE__))))
accounts.push @account.to_h
File.open(File.expand_path('../../db/ebay_accounts', __FILE__), 'w') do |f|
f.write(accounts.to_json)
end
end
def retrieve_IP
@ip = IP.new(@IP_list, @CONFIG_list)
loop do
if @ip.already_used?
@ip.change
else
break
end
sleep 1
end
end
def generate_user
User.new(random_email)
end
def random_email
@email = @EMAIL_list.sample
end
end
|
require 'json'
require 'yaml'
VAGRANTFILE_API_VERSION ||= "2"
confDir = $confDir ||= File.expand_path("vendor/laravel/homestead", File.dirname(__FILE__))
homesteadYamlPath = "Homestead.yaml"
homesteadJsonPath = "Homestead.json"
afterScriptPath = "after.sh"
aliasesPath = "aliases"
require File.expand_path(confDir + '/scripts/homestead.rb')
Vagrant.configure(VAGRANTFILE_API_VERSION) do |config|
if File.exists? aliasesPath then
config.vm.provision "file", source: aliasesPath, destination: "~/.bash_aliases"
end
if File.exists? homesteadYamlPath then
homesteadConfig = YAML::load(File.read(homesteadYamlPath))
Homestead.configure(config, homesteadConfig)
elsif File.exists? homesteadJsonPath then
homesteadConfig = JSON.parse(File.read(homesteadJsonPath))
Homestead.configure(config, homesteadConfig)
end
aliases = []
homesteadConfig['sites'].each do |site|
aliases.push(site['map'])
end
if Vagrant.has_plugin? 'vagrant-hostmanager' then
config.hostmanager.enabled = true
config.hostmanager.manage_host = true
config.hostmanager.aliases = aliases
else
fail_with_message "vagrant-hostmanager missing, please install the plugin with this command:\nvagrant plugin install vagrant-hostmanager"
end
if File.exists? afterScriptPath then
config.vm.provision "shell", path: afterScriptPath
end
end
def fail_with_message(msg)
fail Vagrant::Errors::VagrantError.new, msg
end
|
class Token
def initialize
@lock= false
end
def lock!
if locked?
raise RuntimeError, 'Tried to lock a locked Token.'
else
@lock = true
end
self
end
def type
self.class
end
def is_type?(type)
self.type.eql? type
end
def unlock!
if unlocked?
raise RuntimeError, 'Tried to unlock an unlocked Token.'
else
@lock = false
end
self
end
def locked?
@lock == true
end
def unlocked?
@lock == false
end
#hooks which can be overridden in child classes
def reached_node(node); end
def left_node(node); end
def reached_edge(edge); end
def left_edge(edge); end
end |
class Pet < ApplicationRecord
belongs_to :kind
belongs_to :owner
validates :name, presence: true
validates :birth, presence: true
validates :breed, presence: true
end
|
class AddCountToList < ActiveRecord::Migration
def change
add_column :lists, :perfect_count, :integer
add_column :lists, :current_perfect_streak, :integer
add_column :lists, :longest_perfect_streak, :integer
end
end
|
# This file should contain all the record creation needed to seed the database with its default values.
# The data can then be loaded with the rake db:seed (or created alongside the db with db:setup).
#
# Examples:
#
# cities = City.create([{ name: 'Chicago' }, { name: 'Copenhagen' }])
# Mayor.create(name: 'Emanuel', city: cities.first)
Restaurant.destroy_all
restaurants = [
{
name: 'The Med',
address: '1002 Walnut street',
city: 'Boulder, CO',
image_url: 'http://www.themedboulder.com/images/med-logo.png',
dishes: [
{
name: 'Pomodori E Mozzarella',
price: 10.95,
image_url: 'http://s3-media3.ak.yelpcdn.com/bphoto/YLDNjOu7t31HBCjPsg4EMw/l.jpg'
},
{
name: 'Bolognese',
price: 11.95,
image_url: 'http://www.dashrecipes.com/images/recipes/dr/d/dan-marino-pasta-bolognese_getty-images.jpg'
},
{
name: 'Ravioli Raimondo',
price: 16.95,
image_url: 'http://2.bp.blogspot.com/_bv1UHtcZ51k/S8MOKrTe0eI/AAAAAAAABas/ednqOamOX1I/s1600/InVinoRav.jpg'
},
{
name: 'Fazzoletti',
price: 17.95,
image_url: 'http://whatdidyoueat.typepad.com/photos/uncategorized/2008/01/17/img_1534.jpg'
},
{
name: 'Pollo Parmigiana',
price: 17.95,
image_url: 'http://www.bonappetit.com/images/magazine/2008/09/mare_chicken_parmesan_h.jpg'
}
]
}
{
name: "boulder cafe",
address: "2423 boxwood court",
city: "Boulder",
image_url: "http://media-cdn.tripadvisor.com/media/photo-s/01/1c/c1/5a/boulder-cafe.jpg",
dishes: [
]
}
]
restaurants.each do |restaurant|
r = Restaurant.new name: restaurant[:name], address: restaurant[:address], city: restaurant[:city]
r.save
restaurant[:dishes].each do |dish|
d = Dish.new name: dish[:name], price: dish[:price], image_url: dish[:image_url], restaurant_id: r.id
d.save
end
end
puts "======================"
puts "created #{restaurants.length} restaurants"
puts "======================"
|
class AddDefaultPicture < ActiveRecord::Migration[5.1]
def change
change_column_default :users, :image_url, "http://res.cloudinary.com/lara-cloud1/image/upload/v1513540313/default-profile-picture_gs9kae.png"
end
end
|
require_relative 'lib/share_activerecord_models/version'
Gem::Specification.new do |s|
s.name = 'share_activerecord_models'
s.version = ShareActiveRecordModels::Version::VERSION
s.date = ShareActiveRecordModels::Version::DATE
s.summary = 'Share your ActiveRecord models!'
s.description = 'Barebones gem describing you how to share your models'\
'between multiple projects while keep all your rails magic'
s.authors = 'Mario Carrion'
s.email = 'info@carrion.ws'
s.homepage = 'https://github.com/mariocarrion/share-activerecord-models'
s.licenses = ['MIT']
s.files = `git ls-files`.split("\n")
s.test_files = `git ls-files -- {spec}`.split("\n")
s.require_path = 'lib'
s.required_ruby_version = '~> 2.2'
s.add_runtime_dependency 'activemodel', '~> 4.2', '>= 4.2.5'
s.add_runtime_dependency 'activerecord', '~> 4.2', '>= 4.2.5'
s.add_runtime_dependency 'activesupport', '~> 4.2.5', '>= 4.2.5'
s.add_runtime_dependency 'pg', '~> 0.18', '>= 0.18.2'
s.add_development_dependency 'database_cleaner', '~> 1.4'
s.add_development_dependency 'factory_girl', '~> 4.5', '>= 4.5.0'
s.add_development_dependency 'geminabox', '~> 0.12'
s.add_development_dependency 'pronto', '~> 0.4', '>= 0.4.3'
s.add_development_dependency 'pronto-rubocop', '~> 0.4', '>= 0.4.7'
s.add_development_dependency 'pry', '~> 0.10'
s.add_development_dependency 'pry-nav', '~> 0.2'
s.add_development_dependency 'rails', '~> 4.2.5', '>= 4.2.5.1'
s.add_development_dependency 'rake', '~> 10.4', '>= 10.4.2'
s.add_development_dependency 'rspec', '~> 3.2'
s.add_development_dependency 'rubocop', '~> 0.37'
s.add_development_dependency 'rubocop-checkstyle_formatter', '~> 0.2'
s.add_development_dependency 'rubocop-rspec', '~> 1.4'
s.add_development_dependency 'scenic', '~> 1.2', '>= 1.2.0'
s.add_development_dependency 'shoulda-matchers', '~> 3.0'
s.add_development_dependency 'simplecov', '~> 0.9', '>= 0.9.1'
s.add_development_dependency 'simplecov-rcov', '~> 0.2', '>= 0.2.3'
s.add_development_dependency 'simplecov-summary', '~> 0.0.4'
end
|
module RECMA
module JS
class Math < Base
def initialize
super
self['PI'] = ::Math::PI
end
end
end
end
|
class News < ApplicationRecord
validates_uniqueness_of :url, scope: [:title, :summary]
belongs_to :sources, required: false
belongs_to :categories, required: false
has_and_belongs_to_many :users
end
|
class TodosController < ApplicationController
respond_to :html, :js
def index
@todos = Todo.all
@todo = Todo.new
authorize @todos
end
def new
@todo = Todo.new
authorize @todo
end
def show
@todo = Todo.find params[:id]
authorize @todo
end
def create
@todo = current_user.todos.build(todo_params)
authorize @todo
if @todo.save
flash[:notice] = "Your new TODO was saved."
redirect_to todos_path
else
flash[:error] = "Could not save the TODO."
render :index
end
end
def destroy
@todo = Todo.find params[:id]
authorize @todo
desc = @todo.description
if @todo.destroy
flash[:notice] = "The todo #{desc} was deleted successfully."
else
flash[:error] = "There was an error deleting the Todo item"
end
respond_with(@todo) do |f|
f.html { redirect_to event_hospitality_assignments}
end
end
private
def todo_params
params.require(:todo).permit(:description)
end
end
|
# encoding: utf-8
require 'spec_helper'
describe ValidateEmail do
describe '.valid?' do
it 'returns true when passed email has valid format' do
expect(ValidateEmail.valid?('user@gmail.com')).to be_truthy
expect(ValidateEmail.valid?('valid.user@gmail.com')).to be_truthy
end
it 'returns false when passed email has invalid format' do
expect(ValidateEmail.valid?('user@gmail.com.')).to be_falsey
expect(ValidateEmail.valid?('user.@gmail.com')).to be_falsey
expect(ValidateEmail.valid?('Hgft@(()).com')).to be_falsey
end
context 'when mx: true option passed' do
it 'returns true when mx record exist' do
expect(ValidateEmail.valid?('user@gmail.com', mx: true)).to be_truthy
end
it "returns false when mx record doesn't exist" do
expect(ValidateEmail.valid?('user@example.com', mx: true)).to be_falsey
end
end
context 'when domain: true option passed' do
context 'with valid domains' do
valid_domains = [
'example.org',
'0-mail.com',
'0815.ru',
'0clickemail.com',
'test.co.uk',
'fux0ringduh.com',
'girlsundertheinfluence.com',
'h.mintemail.com',
'mail-temporaire.fr',
'mt2009.com',
'mega.zik.dj',
'e.test.com',
'a.aa',
'test.xn--clchc0ea0b2g2a9gcd',
'my-domain.com',
]
valid_domains.each do |valid_domain|
it "returns true for #{valid_domain}" do
email = "john@#{valid_domain}"
expect(ValidateEmail.valid?(email, domain: true)).to be_truthy
end
end
end
context 'with invalid domain' do
invalid_domains = [
'-eouae.test',
'oue-.test',
'oeuoue.-oeuoue',
'oueaaoeu.oeue-',
'ouoeu.eou_ueoe',
'тест.рф',
'.test.com',
'test..com',
'test@test.com',
"example.org$\'",
]
invalid_domains.each do |invalid_domain|
it "returns false for #{invalid_domain}" do
email = "john@#{invalid_domain}"
expect(ValidateEmail.valid?(email, domain: true)).to be_falsey
end
end
end
end
end
describe '.valid_local?' do
it 'returns false if the local segment is too long' do
expect(
ValidateEmail.valid_local?(
'abcdeabcdeabcdeabcdeabcdeabcdeabcdeabcdeabcdeabcdeabcdeabcdeabcde'
)
).to be_falsey
end
it 'returns false if the local segment has an empty dot atom' do
expect(ValidateEmail.valid_local?('.user')).to be_falsey
expect(ValidateEmail.valid_local?('.user.')).to be_falsey
expect(ValidateEmail.valid_local?('user.')).to be_falsey
expect(ValidateEmail.valid_local?('us..er')).to be_falsey
end
it 'returns false if the local segment has a special character in an unquoted dot atom' do
expect(ValidateEmail.valid_local?('us@er')).to be_falsey
expect(ValidateEmail.valid_local?('user.\\.name')).to be_falsey
expect(ValidateEmail.valid_local?('user."name')).to be_falsey
end
it 'returns false if the local segment has an unescaped special character in a quoted dot atom' do
expect(ValidateEmail.valid_local?('test." test".test')).to be_falsey
expect(ValidateEmail.valid_local?('test."test\".test')).to be_falsey
expect(ValidateEmail.valid_local?('test."te"st".test')).to be_falsey
expect(ValidateEmail.valid_local?('test."\".test')).to be_falsey
end
it 'returns true if special characters exist but are properly quoted and escaped' do
expect(ValidateEmail.valid_local?('"\ test"')).to be_truthy
expect(ValidateEmail.valid_local?('"\\\\"')).to be_truthy
expect(ValidateEmail.valid_local?('test."te@st".test')).to be_truthy
expect(ValidateEmail.valid_local?('test."\\\\\"".test')).to be_truthy
expect(ValidateEmail.valid_local?('test."blah\"\ \\\\"')).to be_truthy
end
it 'returns true if all characters are within the set of allowed characters' do
expect(ValidateEmail.valid_local?('!#$%&\'*+-/=?^_`{|}~."\\\\\ \"(),:;<>@[]"')).to be_truthy
end
end
describe '.mx_valid?' do
let(:dns) { double(Resolv::DNS) }
let(:dns_resource) { double(Resolv::DNS::Resource::IN::MX) }
let(:dns_resource_a) { double(Resolv::DNS::Resource::IN::A) }
let(:exchange) { double(Resolv::DNS::Name) }
before do
expect(Resolv::DNS).to receive(:new).and_return(dns)
expect(dns).to receive(:close)
end
it "returns true when MX is true and it doesn't timeout" do
expect(dns).to receive(:getresources).and_return [dns_resource]
expect(dns_resource).to receive(:exchange).and_return exchange
expect(exchange).to receive(:length).and_return(1)
expect(ValidateEmail.mx_valid?('aloha@kmkonline.co.id')).to be_truthy
end
it "returns false when MX is false and it doesn't timeout" do
expect(dns).to receive(:getresources).and_return []
expect(ValidateEmail.mx_valid?('aloha@ga-ada-mx.com')).to be_falsey
end
it "returns config.default when times out" do
expect(Timeout).to receive(:timeout).and_raise(Timeout::Error)
expect(ValidateEmail.mx_valid?('aloha@ga-ada-mx.com')).to eq(ValidEmail.dns_timeout_return_value)
end
it "returns false when domain doest have mx server" do
expect(dns).to receive(:getresources).and_return [dns_resource]
expect(dns_resource).to receive(:exchange).and_return exchange
expect(exchange).to receive(:length).and_return(0)
expect(ValidateEmail.mx_valid?('aloha@yaho.com')).to be_falsey
end
context "timeout params" do
it "can accept timeout params to overide timeout config" do
timeout = 10
expect(Timeout).to receive(:timeout).with(timeout)
ValidateEmail.mx_valid?('aloha@yaho.com', {timeout: timeout})
end
it "using default timeout config when params timeout not set" do
expect(ValidEmail).to receive(:dns_timeout).and_return(2)
expect(Timeout).to receive(:timeout).with(2)
ValidateEmail.mx_valid?('aloha@yaho.com')
end
end
context "fallback params" do
it "doesnt check A record when fallback params not set" do
expect(dns).to receive(:getresources).with('yaho.com', Resolv::DNS::Resource::IN::MX).and_return [dns_resource]
expect(dns_resource).to receive(:exchange).and_return exchange
expect(exchange).to receive(:length).and_return(1)
expect(dns).not_to receive(:getresources).with('yaho.com', Resolv::DNS::Resource::IN::A)
ValidateEmail.mx_valid?('aloha@yaho.com')
end
it "can accept fallback params to check A record" do
expect(dns).to receive(:getresources).with('yaho.com', Resolv::DNS::Resource::IN::MX).and_return [dns_resource]
expect(dns_resource).to receive(:exchange).and_return exchange
expect(exchange).to receive(:length).and_return(1)
expect(dns).to receive(:getresources).with('yaho.com', Resolv::DNS::Resource::IN::A).and_return [dns_resource_a]
ValidateEmail.mx_valid?('aloha@yaho.com', {fallback: true})
end
end
context "dns_timeout_return_value params" do
before do
expect(Timeout).to receive(:timeout).and_raise(Timeout::Error)
end
it "overide config dns_timeout_return_value when params dns_timeout_return_value present" do
allow(ValidEmail).to receive(:dns_timeout_return_value).and_return(true)
expect(ValidateEmail.mx_valid?('aloha@kmklabs.com', {dns_timeout_return_value: false})).to be_falsey
end
it "use config dns_timeout_return_value when params dns_timeout_return_value not present" do
allow(ValidEmail).to receive(:dns_timeout_return_value).and_return(true)
expect(ValidateEmail.mx_valid?('aloha@kmklabs.com')).to be_truthy
end
end
end
describe ".ban_disposable_email?" do
context "domain is empty" do
it "returns false" do
expect(ValidateEmail.ban_disposable_email?("name@")).to eq false
end
end
context "domain is not empty" do
context "domain exists in disposable dictionary" do
it "returns false" do
expect(ValidateEmail.ban_disposable_email?("name@mailnator.com")).to eq false
end
end
context "domain doesn't exist in disposable dictionary" do
it "returns true" do
expect(ValidateEmail.ban_disposable_email?("name@domain-does-not-exists-in-dictionary.com")).to eq true
end
end
end
end
describe ".matched_disposable_domain" do
context "domain doesn't exists" do
it "returns empty array" do
domains = ValidateEmail.matched_disposable_domain("domain-does-not-exists-in-dictionary.com")
expect(domains).to be_empty
end
end
context "top level domain exists" do
it "returns array of matched TLD" do
domains = ValidateEmail.matched_disposable_domain("effing-spammer-that-is-not-in-the-dictionary.tk")
expect(domains).to include "tk"
end
it "does not return domain name that has the blacklisted TLD in the name" do
domains = ValidateEmail.matched_disposable_domain("playground-tk-sd-smp-sma-kuliah.com")
expect(domains).to be_empty
end
end
context "top level domain name exists" do
it "returns array of matched domain" do
domains = ValidateEmail.matched_disposable_domain("mailinator.com")
expect(domains).to include "mailinator.com"
end
end
end
end
|
module IOTA
module Crypto
class JCurl
NUMBER_OF_ROUNDS = 81
HASH_LENGTH = 243
STATE_LENGTH = 3 * HASH_LENGTH
if RUBY_PLATFORM =~ /java/
require 'jcurl'
com.vmarakana.JCurlService.new.basicLoad(JRuby.runtime)
end
def version
"Java"
end
end
end
end
|
require "rubygems"
require "rake/gempackagetask"
require "rake/rdoctask"
require "spec"
require "spec/rake/spectask"
Spec::Rake::SpecTask.new do |t|
t.spec_opts = %w(--format specdoc --colour)
t.libs = ["spec"]
end
task :default => ["spec"]
spec = Gem::Specification.new do |s|
s.name = "plugin_manager"
s.version = "1.1"
s.summary = "A Ruby plugin loader"
s.author = "Daniel Lucraft"
s.email = "dan@fluentradical.com"
s.homepage = "http://github.com/danlucraft/plugin_manager"
s.has_rdoc = true
s.extra_rdoc_files = %w(README.md)
s.rdoc_options = %w(--main README.md)
s.files = %w(README.md) + Dir.glob("{bin,spec,lib/**/*}")
s.executables = FileList["bin/**"].map { |f| File.basename(f) }
s.require_paths = ["lib"]
s.add_development_dependency("rspec")
end
# This task actually builds the gem. We also regenerate a static
# .gemspec file, which is useful if something (i.e. GitHub) will
# be automatically building a gem for this project. If you're not
# using GitHub, edit as appropriate.
Rake::GemPackageTask.new(spec) do |pkg|
pkg.gem_spec = spec
# Generate the gemspec file for github.
file = File.dirname(__FILE__) + "/#{spec.name}.gemspec"
File.open(file, "w") {|f| f << spec.to_ruby }
end
# Generate documentation
Rake::RDocTask.new do |rd|
rd.main = "README.md"
rd.rdoc_files.include("README.md", "lib/**/*.rb")
rd.rdoc_dir = "rdoc"
end
desc 'Clear out RDoc and generated packages'
task :clean => [:clobber_rdoc, :clobber_package] do
rm "#{spec.name}.gemspec"
end
|
class AddFieldsetToTeamTasks < ActiveRecord::Migration
def change
add_column :team_tasks, :fieldset, :string, null: false, default: ""
add_index :team_tasks, :fieldset
end
end
|
class AddEmailIndexToUsers < ActiveRecord::Migration[5.2]
def change
add_index :users, :email, unique: true
add_index :admins, :email, unique: true
add_index :admins, :personal_id, unique: true
add_index :routes, :code
add_index :stations, :code, unique: true
add_index :buses, :code, unique: true
end
end
|
require 'spec_helper'
describe Rating do
before(:each) do
@question = create(:question)
@customer = Customer.create(email: "thisisfake@gmail.com", full_name: "John Smith")
@product_review = ProductReview.create(product_id: 1, customer_id: @customer.id, comment: "hi")
end
it 'can create a new rating' do
rating = Rating.new(question_id: @question.id, rating: 2, product_review_id: @product_review.id)
expect(rating).to be_valid
end
it 'has a valid factory'do
expect(FactoryGirl.build(:rating)).to be_valid
end
describe 'making new ratings' do
it 'creates multiple new ratings at a time' do
question1 = create(:question)
question2 = create(:durability_question)
question3 = create(:packaging_question)
question4 = create(:description_accuracy_question)
product = create(:product)
product_review = create(:product_review, product: product)
#create the ratings
ratings = [
{question_id: question1.id, rating: 5 },
{question_id: question2.id, rating: 3 },
{question_id: question3.id, rating: 2 },
{question_id: question4.id, rating: 1 }
]
expect{ Rating.make_new_ratings(ratings, product_review.id) }.to change(Rating, :count).by(4)
end
end
end
|
require 'rails/generators'
module Hydra
class InstallGenerator < Rails::Generators::Base
desc 'Generate a new hydra project'
def run_other_generators
Bundler.with_clean_env do
generate("blacklight:install --devise")
generate('hydra:head -f')
rake('db:migrate')
end
end
end
end
|
class User < ActiveRecord::Base
acts_as_authentic
attr_accessible :admin_flag, :password, :crypted_password, :password_salt, :persistence_token,:password_confirmation,:username, :email
has_many :posts
has_many :comments
validates :username, :presence => true
validates :password, :presence => true , :on => :create
end
|
#!/usr/bin/env ruby
require 'rubygems'
require 'rainbow'
require 'net/http'
require 'highline/import'
require 'dnsimple'
# We can't transfer these via the API for
# one reason or another
BAD_TLDS = [".us", ".aero", ".ca"]
if RUBY_VERSION < "1.9"
puts
puts "--- ATTENTION ---".color(:red).bright.blink
puts "You appear to be on Ruby 1.8. Highline acts weird on 1.8 when retrying after an exception."
puts "I recommend you hop up to 1.9.2. But it's OK. Whatever. It's not like I know"
puts "anything about how I run or anything. NO NO. DONT LISTEN TO ME."
puts "--- ATTENTION ---".color(:red).bright.blink
puts
require 'fastercsv'
CSVModule = FasterCSV
else
require 'csv'
CSVModule = CSV
end
puts "Ready to ditch GoDaddy?" + " LET'S DO THIS THING.".color(:red).bright
puts
puts "First, I need your DNSimple details.".color(:magenta)
user = nil
begin
DNSimple::Client.username = ask("What's your username?".bright)
DNSimple::Client.password = ask("What's your password?".bright) { |q| q.echo = "*" }
user = DNSimple::User.me
rescue DNSimple::AuthenticationFailed
puts
puts "ZOMG WTF AUTHENTICATION FAILED!!!".color(:red).bright.blink
puts
retry
end
puts "\nOK, you're logged in now.".color(:yellow) + " Amazing, I know, right?\n".bright.color(:yellow)
contact = nil
if DNSimple::Contact.all.empty?
puts "Hm, well it turns out you don't have contacts setup in DNSimple."
puts "You can either setup one up on dnsimple.com or we can do it here."
puts
puts "What say ye? Do it here or the web?".color(:magenta)
choice = ask("Say 'here' or 'web': ") {|q| q.validate = /(^here$)|(^web$)/ }
if choice == 'web'
puts
puts "PEACE OUT FOR NOW!".bright.color(:blue).blink.italic.background(:yellow)
puts "You come back now, ya here?"
puts
exit
end
puts
puts "OK, let's get the data we need...".bright.color(:cyan)
begin
fn = ask("First name: ") {|q| q.validate = /.+/ }
ln = ask("Last name: ") {|q| q.validate = /.+/ }
address = ask("Address: ") {|q| q.validate = /.+/ }
city = ask("City: ") {|q| q.validate = /.+/ }
state = ask("State: ") {|q| q.validate = /.+/ }
postal_code = ask("Postal code: ") {|q| q.validate = /.+/ }
country = ask("Country: ") {|q| q.validate = /.+/ }
email_address = ask("E-mail: ") {|q| q.validate = /.+/ }
phone = ask("Phone: ") {|q| q.validate = /.+/ }
begin
contact = DNSimple::Contact.create({
:first_name => fn,
:last_name => ln,
:address1 => address,
:city => city,
:state_province => state,
:country => country,
:postal_code => postal_code,
:email_address => email_address,
:phone => phone
})
rescue DNSimple::Error
puts "WHAT DID YOU DO?".bright.color(:red) + " Something broke.".color(:red)
puts "Maybe you put in some bad data. Let's try this again."
puts
retry
end
end
puts
puts "Yay!".color(:yellow).bright + " Contact created."
puts
end
unless contact
contacts = DNSimple::Contact.all
puts "You have to pick a registrant for your domains."
puts
choose do |menu|
menu.prompt = "CHOOSE ONE. QUICKLY.".bright.color(:magenta)
contacts.each do |possible_contact|
menu.choice("#{possible_contact.first_name} #{possible_contact.last_name}") { contact = possible_contact }
end
end
end
puts
file_path = nil
begin
puts "Next, tell me where your data export from GoDaddy is at.\n(Follow instructions here: http://is.gd/2vI0aV)\n".color(:magenta)
file_path = ask("Where is the data file at?".bright)
puts File.join(Dir.pwd, file_path)
unless File.exists?(file_path)
raise "File fail."
end
rescue
puts
puts "ZOMG WTF FILE NOT FOUND!!!".color(:red).bright.blink
puts
retry
end
puts "\nFile found, now slurpinating it.".bright.color(:yellow)
csv = CSVModule.new(File.open(file_path), :headers => true, :skip_blanks => true)
puts
puts "OK, this is getting serious now."
puts "Should I just transfer every domain I can or ask you about each one?".color(:cyan).bright
prompt = ask("Say 'ask' or 'transfer': ") {|q| q.validate = /(^ask$)|(^transfer$)/ }
prompt = (prompt == "ask")
puts
csv.each do |row|
if prompt
response = ask("Transfer " + row['DomainName'].bright.color(:yellow) + " to DNSimple? (yes/no)") {|q| q.validate = /(^yes$)|(^no$)/ }
if response == 'no'
puts "\tOK, cow(boy|girl). Skipping that guy..."
puts
next
end
end
puts "Transferring #{row['DomainName'].bright.color(:yellow)}..."
if row['Locked'] != 'Unlocked'
puts "\t!".color(:red).bright + " Oops. You didn't unlock that domain according to this export. Skipping..."
next
end
if BAD_TLDS.include?(row['TLD'])
puts "\t!".color(:red).bright + " O NOEZ. You can't actually transfer a domain with the TLD #{row['TLD']} via the API. Skipping..."
end
begin
DNSimple::TransferOrder.create(row['DomainName'], row['AuthorizationCode'], {:id => contact.id})
puts "\t*".color(:cyan).bright + " That worked!"
rescue StandardError
# There's a bug in the DNSimple gem...
puts "\t! Well, poop. There seems to be an error.".color(:red)
rescue DNSimple::Error => e
puts "\tWell, poop. There seems to be an error.".color(:red)
puts "\t#{e.message}"
end
end
puts
puts "Well, we're all done. Our time together was magical.".color(:cyan)
puts "I hope it was as good for you as it was for me. ktnxbai"
puts "Visit me at http://arcturo.com sometime."
puts
puts "--- IMPORTANT ---".color(:magenta).bright.blink
puts "To speed up the process, follow the instructions here for"
puts "explicitly approving the transfers: http://is.gd/ZRBLUP"
puts "Takes much less time than the 5 days it normally takes."
puts "--- IMPORTANT ---".color(:magenta).bright.blink
puts |
shared_examples_for 'support interface matcher' do |name|
describe 'interface' do
let(:stdout) { '1000' }
describe interface(name) do
its(:speed) { should eq 1000 }
end
describe interface('invalid-interface') do
its(:speed) { should_not eq 100 }
end
end
end
|
class Region < ActiveRecord::Base
validates :name, presence: true
belongs_to :country
has_many :city, dependent: :destroy
has_many :hostel, as: :location, dependent: :destroy
end
|
# frozen_string_literal: true
require 'rails_helper'
RSpec.describe 'widgets', type: :request do
let!(:user) { FactoryBot.create(:user) }
let!(:user_widget1) { FactoryBot.create(:widget, user: user) }
let!(:user_widget2) { FactoryBot.create(:widget, user: user) }
let!(:other_widget) { FactoryBot.create(:widget) }
let(:token) do
FactoryBot.create(:access_token, resource_owner_id: user.id).token
end
let(:unauth_headers) do
{
'Content-Type' => 'application/json',
}
end
let(:auth_headers) do
unauth_headers.merge(
'Authorization' => "Bearer #{token}",
)
end
describe '#index' do
context 'when unauthenticated' do
it 'returns hard-coded sample widgets' do
get '/widgets'
expect(response).to be_successful
widgets = JSON.parse(response.body)
expect(widgets).to eq([
{
'id' => 1,
'name' => 'Widget 1',
},
{
'id' => 2,
'name' => 'Widget 2',
},
])
end
end
context 'when authenticated' do
it "returns user's widgets" do
get '/widgets', headers: auth_headers
expect(response).to be_successful
widgets = JSON.parse(response.body)
expect(widgets).to eq([
{
'id' => user_widget1.id,
'name' => user_widget1.name,
},
{
'id' => user_widget2.id,
'name' => user_widget2.name,
},
])
end
end
end
describe '#show' do
context 'when unauthenticated' do
it 'returns unauthorized' do
get "/widgets/#{user_widget1.id}"
expect(response).to be_unauthorized
expect(response.body).to eq('')
end
end
context 'when authenticated' do
it "returns user's widget" do
get "/widgets/#{user_widget1.id}", headers: auth_headers
expect(response).to be_successful
widget = JSON.parse(response.body)
expect(widget).to eq(
'id' => user_widget1.id,
'name' => user_widget1.name,
)
end
it "errors on another user's widget" do
expect {
get "/widgets/#{other_widget.id}", headers: auth_headers
}.to raise_error(ActiveRecord::RecordNotFound)
end
end
end
describe '#create' do
name = 'New Widget'
body = {name: name}
context 'when unauthenticated' do
it 'returns unauthorized' do
expect {
post '/widgets',
headers: unauth_headers,
params: body.to_json
}.not_to(change { Widget.count })
expect(response).to be_unauthorized
end
end
context 'when authenticated' do
it 'saves and returns a new widget' do
expect {
post '/widgets', headers: auth_headers, params: body.to_json
}.to change { Widget.count }.by(1)
widget = Widget.last
expect(widget.name).to eq(name)
expect(response).to be_successful
widget_body = JSON.parse(response.body)
expect(widget_body).to eq(
'id' => widget.id,
'name' => name,
)
end
it 'rejects invalid data' do
invalid_body = {name: ''}
expect {
post '/widgets', headers: auth_headers, params: invalid_body.to_json
}.not_to(change { Widget.count })
expect(response.status).to eq(422)
end
end
end
describe '#update' do
updated_name = 'Updated Name'
body = {name: updated_name}
context 'when unauthenticated' do
it 'returns unauthorized' do
patch "/widgets/#{user_widget1.id}",
headers: unauth_headers,
params: body.to_json
expect(response).to be_unauthorized
user_widget1.reload
expect(user_widget1.name).not_to eq(updated_name)
end
end
context 'when authenticated' do
it 'saves changes and returns the updated record' do
patch "/widgets/#{user_widget1.id}", headers: auth_headers, params: body.to_json
user_widget1.reload
expect(user_widget1.name).to eq(updated_name)
expect(response).to be_successful
widget_body = JSON.parse(response.body)
expect(widget_body).to eq(
'id' => user_widget1.id,
'name' => updated_name,
)
end
it "does not allow updating another user's record" do
patch "/widgets/#{other_widget.id}", headers: auth_headers, params: body.to_json
other_widget.reload
expect(other_widget.name).not_to eq(updated_name)
expect(response.status).to eq(401)
end
it 'rejects invalid data' do
invalid_body = {name: ''}
post '/widgets', headers: auth_headers, params: invalid_body.to_json
expect(response.status).to eq(422)
user_widget1.reload
expect(user_widget1.name).not_to eq(updated_name)
end
end
end
describe '#destroy' do
context 'when unauthenticated' do
it 'returns unauthorized' do
expect {
delete "/widgets/#{user_widget1.id}", headers: unauth_headers
}.not_to(change { Widget.count })
expect(response).to be_unauthorized
end
end
context 'when authenticated' do
it 'deletes the record' do
expect {
delete "/widgets/#{user_widget1.id}", headers: auth_headers
}.to change { Widget.count }.by(-1)
expect(response.status).to eq(204)
end
it "does not allow deleting another user's record" do
expect {
delete "/widgets/#{other_widget.id}", headers: auth_headers
}.not_to(change { Widget.count })
expect(response.status).to eq(401)
end
end
end
end
|
require 'omf/job_service/dumper'
module OMF::JobService
class Dumper
class Default < Dumper
def initialize(opts = {})
super
@http_location = "http://#{opts[:http_host]}/dump/#{@db_name}.pg.sql.gz"
@location = "#{@@dump_folder}/#{@db_name}.pg.sql.gz"
end
def dump
`#{dump_cmd}`
$?.exitstatus == 0 ? { success: @http_location } : { error: 'Database dump failed' }
end
private
def dump_cmd
"PGPASSWORD=#{@@db_conn[:password]} pg_dump -O -U #{@@db_conn[:user]} -h #{@@db_conn[:host]} -p #{@@db_conn[:port]} #{@db_name} | gzip > #{@location}"
end
end
end
end
|
describe Rfm::Record do
let(:resultset) {Rfm::Resultset.allocate}
let(:record) {Rfm::Record.allocate}
let(:layout) {Rfm::Layout.allocate}
subject {record}
before(:each) do
record.instance_variable_set(:@portals, Rfm::CaseInsensitiveHash.new)
end
describe ".new" do
context "when model exists" do
it "creates an instance of model" do
rs = Rfm::Resultset.new @Layout, @Layout
#puts rs.layout
#puts rs.layout.model
expect(Rfm::Record.new(rs).class).to eq(Memo)
end
end
context "when no model exists" do
it "creates an instance of Rfm::Record" do
Rfm::Record.new.class == Rfm::Record
end
end
end
describe "#[]" do
before(:each) do
record.instance_variable_set(:@mods, {})
record.instance_variable_set(:@loaded, false)
record['tester'] = 'red'
end
it "returns '' if hash value is '' " do
record['tester'] = ''
record.instance_variable_set(:@loaded, true)
expect(record['tester']).to eql('')
end
it "returns nil if hash value is nil " do
record['tester'] = nil
record.instance_variable_set(:@loaded, true)
expect(record['tester']).to eql(nil)
end
it "raises an Rfm::ParameterError if a key is used that does not exist" do
record.instance_variable_set(:@loaded, true)
record.instance_variable_set(:@layout, layout) # will allow this test to pass
ex = rescue_from { record['tester2'] }
expect(ex.class).to eql(Rfm::ParameterError)
expect(ex.message).to eql('tester2 does not exists as a field in the current Filemaker layout.')
end
it "returns value whether key is string or symbol" do
record.instance_variable_set(:@loaded, true)
expect(record.has_key?(:tester)).to be_falsey
expect(record[:tester]).to eql('red')
end
it "returns value regardless of key case" do
record.instance_variable_set(:@loaded, true)
expect(record['TESTER']).to eq('red')
end
end #[]
describe "#[]=" do
before(:each) do
record.instance_variable_set(:@mods, {})
record.instance_variable_set(:@loaded, false)
record['tester'] = 'red'
end
it "creates a new hash key => value upon instantiation of record" do
expect(record.has_key?('tester')).to be_truthy
expect(record['tester']).to eql('red')
end
it "creates a new hash key as downcase" do
record['UPCASE'] = 'downcase'
expect(record.key?('upcase')).to be_truthy
end
it "creates a new hash key => value in @mods when modifying an existing record key" do
record.instance_variable_set(:@loaded, true)
record['tester'] = 'green'
expect(record.instance_variable_get(:@mods).has_key?('tester')).to be_truthy
expect(record.instance_variable_get(:@mods)['tester']).to eql('green')
end
it "modifies the hash key => value in self whether key is string or symbol" do
record.instance_variable_set(:@loaded, true)
record[:tester] = 'green'
expect(record.has_key?(:tester)).to be_falsey
expect(record['tester']).to eql('green')
end
it "returns '' if hash value is '' " do
record['tester'] = 'something'
record.instance_variable_set(:@loaded, true)
record['tester'] = ''
expect(record['tester']).to eql('')
end
it "returns nil if hash value is nil " do
record['tester'] = 'something'
record.instance_variable_set(:@loaded, true)
record['tester'] = nil
expect(record['tester']).to eql(nil)
end
it "raises an Rfm::ParameterError if a value is set on a key that does not exist" do
record.instance_variable_set(:@loaded, true)
ex = rescue_from { record['tester2'] = 'error' }
expect(ex.class).to eql(Rfm::ParameterError)
expect(ex.message).to match(/You attempted.*Filemaker layout/)
end
it "accepts portal-write notation for portal fields" do
layout.instance_variable_set(:@meta, Rfm::Metadata::LayoutMeta.new(layout).merge!({'field_controls' => {'fakerelationship::fakefield' => Rfm::Metadata::FieldControl.new({'name' => 'FakeRelationship::FakeField'})}}))
record.layout = layout
record.instance_variable_set(:@loaded, true)
record['fakerelationship::fakefield.0'] = 'new portal record'
expect(record['fakerelationship::fakefield.0']).to eq('new portal record')
expect(record.instance_variable_get(:@mods)['fakerelationship::fakefield.0']).to eq('new portal record')
end
end #[]=
describe "#respond_to?" do
it "returns true if key is in hash" do
record['red'] = 'stop'
expect(record.respond_to?(:red)).to be_truthy
end
it "returns false if key is not in hash" do
expect(record.respond_to?(:red)).to be_falsey
end
end
describe "#method_missing" do
before(:each) do
record.instance_variable_set(:@mods, {})
record['name'] = 'red'
end
describe "getter" do
it "will match a method to key in the hash if there is one" do
expect(record.name).to eql('red')
end
it "will raise NoMethodError if no key present that matches value" do
ex = rescue_from { record.namee }
expect(ex.class).to eql(NoMethodError)
expect(ex.message).to match(/undefined method `namee'/)
end
end
describe "setter" do
it "acts as a setter if the key exists in the hash" do
record.instance_variable_set(:@loaded, true)
record.name = 'blue'
expect(record.instance_variable_get(:@mods).has_key?('name')).to be_truthy
expect(record.instance_variable_get(:@mods)['name']).to eql('blue')
end
it "will raise NoMethodError if no key present that matches value" do
ex = rescue_from { record.namee = 'red' }
expect(ex.class).to eql(NoMethodError)
expect(ex.message).to match(/undefined method `namee='/)
end
end
end
describe "#save" do
before(:each) do
record['name'] = 'red'
record.instance_variable_set(:@record_id, 1)
record.instance_variable_set(:@loaded, true)
record.instance_variable_set(:@layout, layout)
record.instance_variable_set(:@mods, {})
allow(layout).to receive(:edit){[record.dup.merge(record.instance_variable_get(:@mods))]}
end
context "when not modified" do
let(:original) {record.dup}
let(:result) {record.save}
it("leaves self untouched"){is_expected.to eq(original)}
it("returns {}"){expect(result).to eq({})}
end
context "when modified" do
before(:each) {record.name = 'green'}
it "passes @mods and @mod_id to layout" do
expect(layout).to receive(:edit).with(1, {'name'=>'green'})
record.save
end
it "merges returned hash from Layout#edit" do
record.instance_variable_get(:@mods)['name'] = 'blue'
record.save
expect(record['name']).to eql('blue')
end
it "clears @mods" do
record.save
expect(record.instance_variable_get(:@mods)).to eql({})
end
it "returns {}" do
expect(record.save).to eql({})
end
end
end #save
describe "#save_if_not_modified" do
before(:each) {
record['name'] = 'red'
record.instance_variable_set(:@record_id, 1)
record.instance_variable_set(:@loaded, true)
record.instance_variable_set(:@mod_id, 5)
record.instance_variable_set(:@layout, layout)
record.instance_variable_set(:@mods, {})
allow(layout).to receive(:edit){[record.instance_variable_get(:@mods)]}
}
context "when local record not modified" do
let(:original) {record.dup}
let(:result) {record.save_if_not_modified}
it("leaves self untouched"){is_expected.to eq(original)}
it("returns {}"){expect(result).to eq({})}
end
context "when local record modified" do
before(:each) {record.name = 'green'}
it "passes @mods and @mod_id to layout" do
expect(layout).to receive(:edit).with(1, {'name'=>'green'}, {:modification_id => 5})
record.save_if_not_modified
end
it "merges returned hash from Layout#edit" do
record.instance_variable_get(:@mods)['name'] = 'blue'
record.save_if_not_modified
expect(record['name']).to eql('blue')
end
it "clears @mods" do
record.save_if_not_modified
expect(record.instance_variable_get(:@mods)).to eql({})
end
it "returns {}" do
expect(record.save_if_not_modified).to eql({})
end
end
end #save_if_not_modified
end #Rfm::Record
|
class RootController < ApplicationController
def index
@articles = Article.published.first(4)
@references = Reference.ordered
end
def references
@references = Reference.ordered
end
end
|
class MailDistributor
attr_reader :sender
private :sender
def initialize args
@sender = args.fetch(:sender, outgoing_queue)
end
def distribute message
sender.publish message
end
private
def outgoing_queue
@default_queue ||= TorqueBox::Messaging::Queue.new '/queues/mail_sender'
end
end
|
class ApplicationController < ActionController::Base
# Prevent CSRF attacks by raising an exception.
# For APIs, you may want to use :null_session instead.
# protect_from_forgery with: :exception
protect_from_forgery
skip_before_action :verify_authenticity_token, if: -> { request.format.symbol == :json }
before_action :set_cart
before_action :connect_cart_to_member
def set_cart
Rails.logger.debug "session cart_id: #{session[:cart_id]}"
session[:cart_id] ||= Cart.create.id
end
def connect_cart_to_member
if current_member && !current_cart.member
current_cart.update member_id: current_member.id
end
end
def current_cart
Cart.find(session[:cart_id])
end
end
|
class Text < ActiveRecord::Base
belongs_to :round
belongs_to :game
belongs_to :user
before_save do
self.body_original = self.body.strip
self.body = self.body_original.downcase
end
after_create do
PushMaster.generate_and_push('sms-count')
end
def self.main_rx(from, to, body)
user, is_new = User.find_or_create(from)
sms = self.create(
:body => body,
:user => user
)
Rails.logger.ap("First Word: #{sms.first_word}")
Rails.logger.ap("Message: #{sms.second_word_on}")
case sms.first_word
when "start"
is_new = user.queue
player1, player2 = User.find_next_two_waiting_users
if !player1 || !player2
if is_new
TwilioNumber.send_message("We are now looking for an opponent for you", user)
end
else
player1.queue_time = nil
player2.queue_time = nil
player1.save
player2.save
game = Game.start_game(player1, player2)
if !game
return
end
provider = DungeonMaster::Master.provider_for game, user, sms
provider.run
end
when "nick"
if sms.second_word_on.empty?
TwilioNumber.send_message("You are currently known as: #{user.nickname}. Send 'NICK {new name}' to change nickname.", user)
return
end
user.nickname = sms.second_word_on[0,16]
user.save
TwilioNumber.send_message("You will now be known as: #{user.nickname}", user)
when "h"
TwilioNumber.send_message(ApplicationConfig[:main_menu], user)
when "score"
score = user.get_total_score
TwilioNumber.send_message("Your total score is: #{score.to_i} points", user)
when "rules"
TwilioNumber.send_message(ApplicationConfig[:rules], user)
else
if !is_new
TwilioNumber.send_message("Unknown command. #{ApplicationConfig[:main_menu]}", user)
end
end
end
def self.game_rx(from, to, body)
user, is_new = User.find_or_create(from)
game = Game.find_active(user, to)
sms = self.create(:body => body, :user => user, :game => game)
if game
game.last_text = sms.body
game.save
provider = DungeonMaster::Master.provider_for game, user, sms
provider.run
end
end
def split_message
return self.body_original.split(" ")
end
def first_word
return split_message.shift.strip.downcase
end
def second_word_on
tmp = split_message
tmp.shift
return tmp.join(" ")
end
end
|
# code here!
class School
attr_reader :roster
def initialize(name, roster = {})
@name = name
@roster = roster
end
def add_student(student, grade)
roster[grade] ||= []
roster[grade] << student
end
def grade(grade)
roster[grade]
end
def sort
sorted = {}
roster.each do |grade, students|
sorted[grade] = students.sort
end
sorted
end
end |
require 'pry'
class Song
@@count = 0
@@artists = []
@@genres = []
attr_reader :name, :artist, :genre
def initialize name, artist, genre
@name = name
@artist = artist
@genre = genre
@@count += 1
@@artists << artist
@@genres << genre
end
def self.count
@@count
end
def self.artists
@@artists.uniq
end
def self.genres
@@genres.uniq
end
def self.count_helper(data)
result = {}
data.each do |d|
result[d] ? result[d] += 1 : result[d] = 1
end
result
end
def self.genre_count
self.count_helper(@@genres)
end
def self.artist_count
self.count_helper(@@artists)
end
end
|
module Student::BookBorrow::CreateHelper
def process
create_book_borrow
generate_status
end
def create_book_borrow
::BookBorrow.transaction do
::BookBorrow.create(create_book_borrow_params)
@book = ::Book.find_by(id: @params[:book_id])
@book.update_attributes(quantity_in_stock: @book.quantity_in_stock - 1)
end
end
def generate_status
@status = {
:code => Settings.code.success,
:message => "Thành công",
:data => {
:book => @book
}
}
end
private
def create_book_borrow_params
@params.permit(:user_id, :book_id)
end
end
|
require 'rails_helper'
RSpec.describe LocationRelation, type: :model do
it { should validate_presence_of(:location_id) }
it { should validate_presence_of(:location_group_id) }
it { should belong_to(:location) }
it { should belong_to(:location_group) }
end
|
require 'rails_helper'
RSpec.describe 'review management function', type: :feature do
before do
@book = Book.create(title: "title", author: "author", price: 5000, genre: 5, released_at: "2020-05-05", story: "story", icon: "icon_URL")
@user= User.new(name: "name", introduce: "introduce", icon: "icon_URL", admin: false, email: "test@e.mail", password: "password")
# @user.skip_confirmation!
@user.save
visit new_user_session_path
fill_in "Email", with: @user.email
fill_in "Password", with: @user.password
find(".login_button").click
end
feature 'review detail screen' do
context 'when transistioning to any book detail screen' do
it 'transit to the page where the content, reviews, and comments of the book are displayed' do
@review = Review.create(speciality: 1, knowledge: 1, story: 1, like: 1, summary: "summary", body: "review_body", book_id: @book.id, user_id: @user.id)
visit review_path(@review.id)
expect(page).to have_content @review.summary
expect(page).to have_content @review.speciality
expect(page).to have_content @review.knowledge
expect(page).to have_content @review.story
expect(page).to have_content @review.like
expect(page).to have_content @review.speciality + @review.knowledge + @review.story + @review.like
expect(page).to have_content @review.body
end
end
end
end
|
require 'securerandom'
require 'uri'
require 'net/http'
require 'net/https'
require 'json'
class TransactionStatusWorker
include Sidekiq::Worker
sidekiq_options retry: true
def perform(user_transaction_id)
UserTransaction.transaction do
user_transaction = UserTransaction.find(user_transaction_id)
sender = user_transaction.sender
sender_account = sender.account.profile
formatted_amount = sender.get_formatted_amount(user_transaction.net_amount, user_transaction.country_to)
if user_transaction.status == SmxTransaction.statuses[:pending_]
if user_transaction.recipient_type == SmxTransaction.recipient_types[:international_recep_]
net_amount = user_transaction.net_amount
total_amount = net_amount + user_transaction.fees
sender_account.update!(balance: sender_account.reload.balance + total_amount)
user_transaction.update(status: SmxTransaction.statuses[:cancelled_])
user_transaction.refund_charge
elsif user_transaction.recipient_type == SmxTransaction.recipient_types[:non_smx_recep_]
user_transaction.update(status: SmxTransaction.statuses[:cancelled_])
SmsService.new({phone_number: user_transaction.sender.telephone, first_name: user_transaction.response_hash[:recipient_first_name].capitalize, last_name: user_transaction.response_hash[:recipient_last_name], formatted_amount: formatted_amount}, SmxTransaction.message_types[:smx_non_smx_cancelled_send_])
end
end
end
end
end |
class Category < ApplicationRecord
TYPE = ["mirrorless", "full frame", "point and shoot"]
has_many :products
validates :category_type , :inclusion => { :in => TYPE , :message => "Type must be within #{TYPE}"}
end
|
task delete_items: :environment do
Item.where("created_at <= ?", 7.days.ago).destroy_all
end
|
require 'spec_helper'
#This file tests the content and actions related to the actual user section pages
#eg the content present
describe "User pages" do
subject { page }
#tests for the user index
describe "index" do
before do
sign_in FactoryGirl.create(:user)
FactoryGirl.create(:user, name:"Shane", email: "shane@example.com")
FactoryGirl.create(:user, name:"Henry", email: "henry@example.com")
visit users_path
end
it { should have_title('All users') }
it { should have_content('All users') }
describe "delete links" do
it { should_not have_link('delete') }
describe "as admin user" do
let(:admin){FactoryGirl.create(:admin, name:"admin", email: "admin@example.com")}
before do
sign_in admin
visit users_path
end
it { should have_link('delete', href: user_path(User.first)) }
it "should be able to delete another user" do
expect do
click_link('delete', match: :first)
end.to change(User, :count).by(-1)
end
#make sure no link to delete admin
it { should_not have_link('delete', href: user_path(admin)) }
end
end
it "should list each user" do
User.all.each do |user|
expect(page).to have_selector('li', text: user.name)
end
end
end
#tests for the page showing the user
describe "profile page" do
#call factory user and assign to variable user
let(:user) { FactoryGirl.create(:user) }
#Goto the user page
before do
sign_in user
visit user_path(user)
end
it { should have_content(user.name) }
it { should have_title(user.name) }
end
#tests for the register user page
describe "register page" do
before { visit register_path }
it { should have_content("Register User") }
it { should have_title(full_title('Register User')) }
end
#tests for the registering process
describe "registering" do
before { visit register_path }
#assign hitting the create account button to variable submit
let(:submit) { "Create Account" }
describe "with invalid information" do
#tests checking the non creating of users with invalid info
#check by ensuring user count doesnt increase with submitted
it "should not create user" do
expect { click_button submit }.not_to change(User, :count)
end
describe "after submission" do
#ensure the error messages appear after invalid info
before { click_button submit }
it { should have_title('Register') }
it { should have_content('error') }
end
end
describe "with valid information" do
#tests ensuring creating of users
before do
fill_in "Name", with: "Example User"
fill_in "Email", with: "user@example.com"
fill_in "Password", with: "foobar"
fill_in "Confirmation", with: "foobar"
end
#check by ensuring user count increases on submission
it "should create user" do
expect { click_button submit }.to change(User, :count).by(1)
end
describe "it should redirect to user page" do
before { click_button submit }
let(:user) { User.find_by(email: 'user@example.com') }
it { should have_title(user.name) }
it { should have_content(user.name) }
end
describe "it should show success message" do
before { click_button submit }
let(:user) { User.find_by(email: 'user@example.com') }
it { should have_content('Welcome to the thing') }
end
describe "after saving the user" do
#checking the user gets signed in post saving
before { click_button submit }
let(:user) { User.find_by(email: 'user@example.com') }
it { should have_title(full_title('')) }
it { should_not have_link('Sign in', href: login_path) }
it { should have_link('Sign Out', href: logout_path) }
it { should have_content(user.name) }
end
end
end
describe "edit" do
#all tests relating to the edit user pages
let(:user) { FactoryGirl.create(:user) }
before do
sign_in user
visit edit_user_path(user)
end
describe "with valid information" do
let(:new_name) { "New Name" }
let(:new_email) { "new@example.com" }
before do
fill_in "Name", with: new_name
fill_in "Email", with: new_email
fill_in "Password", with: user.password
fill_in "Confirm", with: user.password
click_button "Save Changes"
end
it { should have_title(new_name) }
it { should have_selector(".success") }
it { should have_link('Sign Out', href: logout_path) }
specify { expect(user.reload.name).to eq new_name }
specify { expect(user.reload.email).to eq new_email }
end
describe "page" do
it { should have_content("Update your profile") }
it { should have_title("Edit user") }
end
describe "with invalid information" do
before { click_button "Save Changes" }
it { should have_content('error') }
end
end
end
|
# http://cdn.cs50.net/2016/x/psets/2/pset2/pset2.html
# INITIALIZING
# You may assume that the users input will contain only letters
# (uppercase and/or lowercase) plus single spaces between words.
def ask_name
puts "What's your name?"
gets.chomp
end
def initialize_name(full_name)
full_name.split.map(&:chr).join.upcase
end
def initial_printer
name = ask_name
initials = initialize_name(name)
puts initials
end
initial_printer
|
require 'ynab'
require 'fileutils'
require 'activesupport/core_ext/module/attribute_accessors'
module YNAB::Configuration
mattr_writer :use_cloud_sync
mattr_writer :ynab_home
mattr_writer :detect_file_changes
def budget_ext
".ynab4"
end
def budget_metadata_ext
".ymeta"
end
def budget_backup_ext
".y4backup"
end
def device_ext
".ydevice"
end
def detect_file_changes
@detect_file_changes ||= false
end
def use_cloud_sync
@use_cloud_sync ||= false
end
def ynab_home
@ynab_home ||= File.join(Dir.home, "Dropbox", "YNAB")
end
end
|
class AddDeviseTwoFactorToUsers < ActiveRecord::Migration[4.2]
def change
add_column :users, :encrypted_otp_secret, :string
add_column :users, :encrypted_otp_secret_iv, :string
add_column :users, :encrypted_otp_secret_salt, :string
add_column :users, :consumed_timestep, :integer
add_column :users, :otp_required_for_login, :boolean
add_column :users, :otp_backup_codes, :string, array: true
end
end
|
# frozen_string_literal: true
require 'spec_helper'
class ClassMethodTest
class << self
def trigger(params); end
def method1
trigger(nil)
end
def method2(arg1)
trigger(arg1)
end
def method3(arg1, arg2)
args = {
arg1: arg1,
arg2: arg2
}
trigger(args)
end
def method4(arg1, arg2:)
args = {
arg1: arg1,
arg2: arg2
}
trigger(args)
end
end
end
RSpec.describe SidekiqSimpleDelay do
before(:all) do
SidekiqSimpleDelay.enable_delay_class!(ClassMethodTest)
end
describe 'delay class methods' do
it 'enqueue simple_delay' do
expect do
ClassMethodTest.simple_delay.method1
end.to change(SidekiqSimpleDelay::SimpleDelayedWorker.jobs, :size).by(1)
expect(ClassMethodTest).to receive(:trigger)
Sidekiq::Worker.drain_all
end
it 'enqueue simple_delay_for' do
expect do
ClassMethodTest.simple_delay_for(1.minute).method1
end.to change(SidekiqSimpleDelay::SimpleDelayedWorker.jobs, :size).by(1)
expect(ClassMethodTest).to receive(:trigger)
Sidekiq::Worker.drain_all
end
it 'enqueue simple_delay_until' do
expect do
ClassMethodTest.simple_delay_until(1.day.from_now).method1
end.to change(SidekiqSimpleDelay::SimpleDelayedWorker.jobs, :size).by(1)
expect(ClassMethodTest).to receive(:trigger)
Sidekiq::Worker.drain_all
end
it 'enqueue simple_delay_spread' do
expect do
ClassMethodTest.simple_delay_spread.method1
end.to change(SidekiqSimpleDelay::SimpleDelayedWorker.jobs, :size).by(1)
expect(ClassMethodTest).to receive(:trigger)
Sidekiq::Worker.drain_all
end
context 'arguments' do
it 'single sting argument' do
ClassMethodTest.simple_delay.method2('simple')
expect(ClassMethodTest).to receive(:trigger).with('simple')
Sidekiq::Worker.drain_all
end
it 'single array argument' do
ClassMethodTest.simple_delay.method2(['simple'])
expect(ClassMethodTest).to receive(:trigger).with(['simple'])
Sidekiq::Worker.drain_all
end
it 'single hash argument' do
args = { 'simple' => 123 }
ClassMethodTest.simple_delay.method2(args)
expect(ClassMethodTest).to receive(:trigger).with(args)
Sidekiq::Worker.drain_all
end
it 'multiple simple arguments' do
ClassMethodTest.simple_delay.method3('things', 'words')
expect(ClassMethodTest).to receive(:trigger).with(arg1: 'things', arg2: 'words')
Sidekiq::Worker.drain_all
end
it 'multiple arguments' do
ClassMethodTest.simple_delay.method3('things', ['words', 123])
expect(ClassMethodTest).to receive(:trigger).with(arg1: 'things', arg2: ['words', 123])
Sidekiq::Worker.drain_all
end
it 'method with keyword arg should raise' do
expect do
ClassMethodTest.simple_delay.method4('things', arg2: 'things')
end.to raise_exception(::ArgumentError)
end
end
end
end
|
require 'rails_helper'
RSpec.describe "Articles", type: :request do
describe "GET /wiki/:article_id" do
let (:article_id) { "Pig_Latin" }
let (:stub_response) {{
"parse" => {
"title" => "Pig Latin",
"text" => "test"
}
}}
context "With article not created" do
it "should call api and create entry" do
expect_any_instance_of(WikipediaApi).to receive(:fetch_article).and_return(stub_response)
expect {
get "/wiki/#{article_id}"
}.to change { Article.count }
expect(response).to have_http_status(:success)
end
end
context "With article created" do
before do
Article.create!(
title: "Pig Latin",
content: "test",
wikipedia_id: article_id
)
end
it "shouldnt call api" do
expect_any_instance_of(WikipediaApi).to_not receive(:fetch_article)
get "/wiki/#{article_id}"
expect(response).to have_http_status(:success)
end
end
end
end
|
json.array!(@subchapters) do |subchapter|
json.extract! subchapter, :id, :es_description, :en_description, :chapter_id
json.url subchapter_url(subchapter, format: :json)
end
|
# The requested command is passed in here as @command
case @command
when "test_ids:rollback"
if ARGV[0]
local = TestIds::Git.path_to_local
TestIds::Git.new(local: local).rollback(ARGV[0])
else
puts "You must supply a commit ID to rollback to, e.g. origen test_ids:rollback 456ac3f53"
end
exit 0
when "test_ids:clear", "test_ids:repair"
require "test_ids/commands/#{@command.split(':').last}"
exit 0
else
@plugin_commands << <<-EOT
test_ids:rollback Rollback the TestIds store to the given commit ID
test_ids:clear Clear the assignment database for bins, softbins, numbers, ranges or all for the given configuration database ID
test_ids:repair Repair the given database, see -h for more
EOT
end
|
require 'active_support/concern'
module Spree::CouponsGiftCertificates::CouponCredit
extend ActiveSupport::Concern
included do
alias :spree_calculate_coupon_credti :calculate_coupon_credit
end
def calculate_coupon_credit
return 0 if order.line_items.empty?
amount = adjustment_source.compute(order.line_items).abs
order_total = adjustment_source.include?('giftcert-') ? order.item_total + order.charges.total : order.item_total
amount = order_total if amount > order_total
-1 * amount
end
end
|
class CreateInvoices < ActiveRecord::Migration
def change
create_table :invoices do |t|
t.references :client, index: true, foreign_key: true
t.references :company, index: true, foreign_key: true
t.date :sendDate
t.date :due_by
t.text :description
t.float :amount
t.string :stripe_payment
t.integer :check_payment
t.date :paid_date
t.timestamps null: false
end
end
end
|
class CreateQueueTaskEmails < ActiveRecord::Migration[5.0]
def change
create_table :queue_task_emails do |t|
t.string :email
t.string :queue_task_emails
t.references :subscriber, index: true, foreign_key: true
t.references :course, index: true, foreign_key: true
t.references :post, index: true, foreign_key: true
t.boolean :sent
t.boolean :opened
t.boolean :bounced
t.datetime :day_to_send
t.timestamps
end
end
end
|
# Read about factories at https://github.com/thoughtbot/factory_girl
FactoryGirl.define do
factory :product do
name "name"
body "body"
sequence(:alias) { |i| "alias#{i}"}
subcategory_id 100
subcategory
price 1
end
end
|
module Jekyll
class IncludeSetTag < Liquid::Tag
#safe true
def initialize(tag_name, files, tokens)
super
@files = files.strip
end
def render(context)
includes_dir = File.join(context.registers[:site].source, '_includes')
pg = context["page"]
filenames = pg[@files]
if ! filenames
return ""
end
if File.symlink?(includes_dir)
return "Includes directory '#{includes_dir}' cannot be a symlink"
end
source = ""
partial = ""
Dir.chdir(includes_dir) do
choices = Dir['**/*'].reject { |x| File.symlink?(x) }
for filename in filenames
if choices.include?(filename)
source = source + File.read(filename)
end
end
end
partial = Liquid::Template.parse(source)
context.stack do
partial.render(context)
end
end
end
end
Liquid::Template.register_tag('includeset', Jekyll::IncludeSetTag)
|
class Album < ApplicationRecord
validates :title, :genre, :year, presence: true
belongs_to :artist
has_many :songs
has_many :follows, as: :followable
end
|
class RecordtleitsController < ApplicationController
before_action :set_recordtleit, only: [:show, :edit, :update, :destroy]
# GET /recordtleits
# GET /recordtleits.json
def index
@recordtleits = Recordtleit.all
end
# GET /recordtleits/1
# GET /recordtleits/1.json
def show
end
# GET /recordtleits/new
def new
@recordtleit = Recordtleit.new
end
# GET /recordtleits/1/edit
def edit
end
# POST /recordtleits
# POST /recordtleits.json
def create
@recordtleit = Recordtleit.new(recordtleit_params)
respond_to do |format|
if @recordtleit.save
format.html { redirect_to @recordtleit, notice: 'Recordtleit was successfully created.' }
format.json { render :show, status: :created, location: @recordtleit }
else
format.html { render :new }
format.json { render json: @recordtleit.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /recordtleits/1
# PATCH/PUT /recordtleits/1.json
def update
respond_to do |format|
if @recordtleit.update(recordtleit_params)
format.html { redirect_to @recordtleit, notice: 'Recordtleit was successfully updated.' }
format.json { render :show, status: :ok, location: @recordtleit }
else
format.html { render :edit }
format.json { render json: @recordtleit.errors, status: :unprocessable_entity }
end
end
end
# DELETE /recordtleits/1
# DELETE /recordtleits/1.json
def destroy
@recordtleit.destroy
respond_to do |format|
format.html { redirect_to recordtleits_url, notice: 'Recordtleit was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_recordtleit
@recordtleit = Recordtleit.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def recordtleit_params
params.require(:recordtleit).permit(:ticket_id, :n1, :n2, :n3, :siglas, :monto, :seleccionada)
end
end
|
=begin
Площадь треугольника.
Площадь треугольника можно вычилсить, зная его основание (a) и высоту (h) по формуле:1/2*a*h.
Программа должна запрашивать основание и высоту треуголиника и возвращать его площадь.
=end
puts "Введите основание треугольника:"
a = gets.chomp
a = a.to_f
#puts "#{a.class}"
puts "Введите высоту треугольника:"
h = gets.chomp
h = h.to_f
#puts "#{h.class}"
if a > 0 && h > 0
puts "Площадь равна: #{s = 0.5 * a * h}"
s = s.to_f
#puts "#{s.class}"
else puts "Ошибка ввода данных! Все числа должны быть положительные!"
end
|
Graphers={
"ST-50"=>"fdp",
"SC-47"=>"dot",
"everything"=>"dot"
}
PageSizes={
"ST-50"=>[8,4],
"SC-47"=>[8,4],
"everything"=>[32,4]
}
def page_size file
PageSizes[file]||[8,4]
end
def goptions(file,s)
s||=1
file=File.basename(file,".dot")
"#{Graphers[file]||'dot'} -Epenwidth=4 -Npenwidth=2 -Estyle=solid -Gfontsize=16 -Gsize=#{page_size(file)[0]*s},#{page_size(file)[1]*s} -Gratio=fill"
end
Scales.each do |s|
rule ".#{s}cmap" => ".dot" do |t|
sh "cat #{t.source} | #{goptions(t.source,s)} -Tcmap -o#{t.name}"
end
rule ".#{s}jpeg" => ".dot" do |t|
sh "cat #{t.source} | #{goptions(t.source,s)} -Tjpeg -Nfontcolor=blue -o#{t.name}"
end
end
rule '.dot' => '.xml' do |t|
sh "provenance-ruby/bin/provenance --in #{t.source} --report artifact_graph > #{t.name}"
end
rule '.report' => '.xml' do |t|
sh "provenance-ruby/bin/provenance --in #{t.source} --report textual > #{t.name}"
end
task 'imgclean' do
rm_rf Dir.glob "#{Resources}**/*.*jpeg"
rm_rf Dir.glob "#{Resources}**/*.cmap"
end
task 'reportclean' do
rm_rf Dir.glob "#{Resources}**/*.report"
end
task 'dotclean' do
rm_rf Dir.glob "#{Resources}**/*.dot"
end
Pages.each do |code|
file "#{resourcepath(code)}#{code}.xml"
file "#{resourcepath(code)}#{code}.dot" => "#{resourcepath(code)}#{code}.xml"
file "#{resourcepath(code)}#{code}.report" => "#{resourcepath(code)}#{code}.xml"
Scales.each do |s|
file "#{resourcepath(code)}#{code}.#{s}cmap" => "#{resourcepath(code)}#{code}.dot"
file "#{resourcepath(code)}#{code}.#{s}jpeg" => "#{resourcepath(code)}#{code}.dot"
end
end |
class SiteAdminsController < ApplicationController
before_action :set_site_admin, only: [:show, :edit, :update, :destroy]
# GET /site_admins
# GET /site_admins.json
def index
@site_admins = SiteAdmin.all
end
# GET /site_admins/1
# GET /site_admins/1.json
def show
end
# GET /site_admins/new
def new
@site_admin = SiteAdmin.new
end
# GET /site_admins/1/edit
def edit
end
# POST /site_admins
# POST /site_admins.json
def create
@site_admin = SiteAdmin.new(site_admin_params)
respond_to do |format|
if @site_admin.save
format.html { redirect_to @site_admin, notice: 'Site admin was successfully created.' }
format.json { render :show, status: :created, location: @site_admin }
else
format.html { render :new }
format.json { render json: @site_admin.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /site_admins/1
# PATCH/PUT /site_admins/1.json
def update
respond_to do |format|
if @site_admin.update(site_admin_params)
format.html { redirect_to @site_admin, notice: 'Site admin was successfully updated.' }
format.json { render :show, status: :ok, location: @site_admin }
else
format.html { render :edit }
format.json { render json: @site_admin.errors, status: :unprocessable_entity }
end
end
end
# DELETE /site_admins/1
# DELETE /site_admins/1.json
def destroy
@site_admin.destroy
respond_to do |format|
format.html { redirect_to site_admins_url, notice: 'Site admin was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_site_admin
@site_admin = SiteAdmin.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def site_admin_params
params[:site_admin]
end
def NGO_requests_control
end
def project_requests_control
end
end
|
class AddAsyncCommandsIndices < ActiveRecord::Migration
def self.up
add_index :async_commands, :next_try_at
add_index :async_commands, :prereq_message_id
end
def self.down
remove_index :async_commands, :prereq_message_id
remove_index :async_commands, :next_try_at
end
end
|
# -*- coding:utf-8 -*-
describe ::PPC::API::Sogou::Keyword do
'''
sogou的关键词服务在add的时候需要审核因此不能一次通过,
会出现keyword is pending的error.不过手动测试方法没问题了。
'''
auth = $sogou_auth
::PPC::API::Sogou.debug_off
test_group_id = ::PPC::API::Sogou::Group::ids( auth )[:result][0][:group_ids][0]
test_keyword_id = []
#::PPC::API::Sogou.debug_on
it 'can search keyword by group id' do
response = ::PPC::API::Sogou::Keyword::search_by_group_id( auth, test_group_id )
is_success( response )
expect(response[:result]).not_to be_nil
end
it 'can add keyword' do
keyword = { group_id: test_group_id, keyword: 'testkeyword123', match_type:'exact' }
response = ::PPC::API::Sogou::Keyword::add( auth, keyword )
is_success( response )
expect(response[:result]).not_to be_nil
test_keyword_id << response[:result][0][:id]
end
it 'can get status' do
response = ::PPC::API::Sogou::Keyword::status( auth, test_keyword_id )
is_success(response)
expect(response[:result][0].keys).to eq [:id,:status]
expect(response[:result]).not_to be_nil
end
it 'can get quality' do
response = ::PPC::API::Sogou::Keyword::quality( auth, test_keyword_id)
is_success(response)
expect(response[:result][0].keys).to eq [:id,:quality]
expect(response[:result]).not_to be_nil
end
it 'can update keyword' do
update = { id: test_keyword_id[0], pause: true}
response = ::PPC::API::Sogou::Keyword::update( auth, update )
is_success( response )
expect(response[:result]).not_to be_nil
end
it 'can delete keyword' do
response = ::PPC::API::Sogou::Keyword::delete( auth, test_keyword_id )
is_success( response )
end
end
|
json.categories @categories do |cat|
json.body cat.title
json.lists cat.lists
end |
class Args
def initialize(arg,list)
@list = list
@args = arg_parser(arg)
end
def printer
print @args
puts ""
end
def include?(arg)
return @args.include?(arg)
end
def [](arg)
return @args[arg]
end
def arg_parser(arg)
args = Hash.new
temp = arg.select {|x| x.include?("-")}
# print temp
# puts
temp.each do |itm|
if @list.include?(itm) && @list[itm]
args[itm] = arg[arg.index(itm)+1]
elsif @list.include?(itm)
args[itm] = nil
else
puts "Unrecognized argument: #{itm}"
exit 1
end
end
# print args
# puts
return args
end
end |
# *******************************************
# This is a demo file to show usage.
#
# @package TheCityAdmin::Admin
# @authors Robbie Lieb <robbie@onthecity.org>, Wes Hays <wes@onthecity.org>
# *******************************************
require 'ruby-debug'
require File.dirname(__FILE__) + '/../lib/the_city_admin.rb'
require File.dirname(__FILE__) + '/city_keys.rb'
include CityKeys
TheCityAdmin::AdminApi.connect(KEY, TOKEN)
puts "------------------------------------"
webhook_list = TheCityAdmin::WebHookList.new
if webhook_list.empty?
puts "No web hooks in list"
else
puts "Web hooks: #{webhook_list.count}"
end
webhook = TheCityAdmin::WebHook.new
webhook.object = TheCityAdmin::WebHook::Objects[:group]
webhook.event = TheCityAdmin::WebHook::Events[:create]
webhook.callback_uri = 'https://www.example.com/mycallback_url'
if webhook.save
puts "Web hook created (#{webhook.id})"
else
puts "Failed to create web hook: #{webhook.error_messages.join(', ')}"
end
webhook_list2 = TheCityAdmin::WebHookList.new
if webhook_list2.empty?
puts "No web hooks in list"
else
puts "Web hooks: #{webhook_list2.count}"
end
if webhook.delete
puts "Web hook #{webhook.id} deleted"
else
puts "Unable to delete web hook #{webhook.id}: #{webhook.error_messages.join(', ')}"
end
webhook_list3 = TheCityAdmin::WebHookList.new
if webhook_list3.empty?
puts "No web hooks in list"
else
puts "Web hooks: #{webhook_list3.count}"
end
puts "####################################"
|
class Admins::HealthCoursesController < ApplicationController
before_action :authenticate_admin!
before_action :ensure_health_course, only: %i[show edit update destroy]
def index
@health_courses = HealthCourse.order(date: 'DESC').page(params[:page]).per(10)
if params[:location]
@health_courses = HealthCourse.where(location: params[:location]).order(date: 'DESC').page(params[:page]).per(10)
end
end
def show
@health_course = HealthCourse.find(params[:id])
end
def new
@health_course = HealthCourse.new
end
def create
@health_course = HealthCourse.new(health_course_params)
if @health_course.save
flash[:success] = '登録が完了しました'
redirect_to admins_health_courses_path(@health_course)
else
render :new
end
end
def edit; end
def update
if @health_course.update(health_course_params)
flash[:success] = '内容を変更しました'
redirect_to admins_health_course_path(@health_course)
else
render :edit
end
end
def destroy
@health_course.destroy
flash[:success] = '削除しました'
redirect_to admins_health_courses_path
end
private
def health_course_params
params.require(:health_course).permit(:title, :contents, :location, :date, :site)
end
def ensure_health_course
@health_course = HealthCourse.find(params[:id])
end
end
|
class ApiController < ApplicationController
def tree
render json: Treeview.tree(params[:path])
end
def file_preview
file = params[:file]
unless File.exists?(file)
return render json: [], status: 404
end
unless File.file?(file) && File.readable?(file)
return render json: [], status: 403
end
render json: file_tail(file)
end
def empty_json
render json: []
end
def regexp_preview
plugin_config = prepare_plugin_config || {}
preview = RegexpPreview.processor(params[:parse_type]).new(params[:file], params[:parse_type], plugin_config)
render json: preview.matches
rescue Fluent::ConfigError => ex
render json: { error: "#{ex.class}: #{ex.message}" }
end
private
def prepare_plugin_config
plugin_config = params[:plugin_config]
case params[:parse_type]
when "multiline"
plugin_config[:formats].lines.each.with_index do |line, index|
plugin_config["format#{index + 1}"] = line.chomp
end
plugin_config
else
plugin_config
end
end
end
|
# frozen_string_literal: true
class Ztimer
# Implements a watcher which allows to enqueue Ztimer::Slot items, that will be executed
# as soon as the time of Ztimer::Slot is reached.
class Watcher
def initialize(&callback)
@thread = nil
@slots = Ztimer::SortedStore.new
@callback = callback
@lock = Mutex.new
@mutex = Mutex.new
end
def <<(slot)
@mutex.synchronize do
@slots << slot
run if @slots.first == slot
end
end
def jobs
@slots.size
end
protected
def run
if @thread
@thread.wakeup
@thread.run
else
start
end
end
def start
@lock.synchronize do
return if @thread
@thread = Thread.new do
loop do
begin
delay = calculate_delay
if delay.nil?
Thread.stop
next
end
select(nil, nil, nil, delay / 1_000_000.to_f) if delay > 1 # 1 microsecond of cranularity
while fetch_first_expired
end
rescue StandardError => e
puts "#{e.inspect}\n#{e.backtrace.join("\n")}"
end
end
end
@thread.abort_on_exception = true
end
end
def calculate_delay
@mutex.synchronize { @slots.empty? ? nil : @slots.first.expires_at - utc_microseconds }
end
def fetch_first_expired
@mutex.synchronize do
slot = @slots.first
if slot && (slot.expires_at < utc_microseconds)
@slots.shift
slot.started_at = utc_microseconds
unless slot.canceled?
execute(slot)
if slot.recurrent?
slot.reset!
@slots << slot
end
end
else
slot = nil
end
slot
end
end
def execute(slot)
@callback.call(slot)
end
def utc_microseconds
Time.now.to_f * 1_000_000
end
end
end
|
require "generators/mail_tracker/mail_tracker_generator"
require "generators/mail_tracker/next_migration_version"
require "rails/generators/migration"
require "rails/generators/active_record"
# Extend the MailTrackerGenerator so that it creates an AR migration
module MailTracker
class ActiveRecordGenerator < ::MailTrackerGenerator
include Rails::Generators::Migration
extend NextMigrationVersion
source_paths << File.join(File.dirname(__FILE__), "templates")
def create_migration_file
migration_template "migration.rb", "db/migrate/create_mail_tracker.rb"
end
def self.next_migration_number(dirname)
ActiveRecord::Generators::Base.next_migration_number dirname
end
end
end
|
require 'httparty'
require 'json'
require './lib/roadmap'
require './lib/messages'
class Kele
include HTTParty
include Roadmap
include Messages
# Creates a new Kele client authorized with a email and password
# Params: email = string, password = string
def initialize(email, password)
# Use the httparty class method .post to send a post request to the sessions endpoint of Bloc’s API with the email and password in the body of the request.
response = self.class.post(api_url("sessions"), body: {"email": email, "password": password})
# The @auth_token instance variable holds the authorization token provided by Bloc's API upon verifying successful email and password.
@auth_token = response["auth_token"]
# If the email and password are invalid, Bloc's API will not return an authorization token.
puts "There was a problem authorizing those credentials. Please try again." if @auth_token.nil?
end
# Bloc's API URL
# Params: endpoint = string
def api_url(endpoint)
"https://www.bloc.io/api/v1/#{endpoint}"
end
# Retrieve's the current user as a JSON blob by passing auth_token to the request to property authenticate against the Bloc API.
# Params: auth_token = string
def get_me
# Point the HTTParty GET method at the users/me endpoint of Bloc's API.
# Use HTTParty's header option to pass the auth_token.
response = self.class.get(api_url('users/me'), headers: { "authorization" => @auth_token })
# Parse the JSON document returned in the response into a Ruby hash.
JSON.parse(response.body)
end
# Retrieve the availability of the current user's mentor
def get_mentor_availability(mentor_id)
# Point the HTTParty GET method at the mentors/mentor_id/student_availability endpoint of Bloc's API.
# Use HTTParty's header option to pass the auth_token.
response = self.class.get(api_url("/mentors/#{mentor_id}/student_availability"), headers: { "authorization" => @auth_token })
# This is the array that will hold all of the time slots that are not booked.
available = []
# Parse the JSON document returned in the response into a Ruby hash.
# Loop through each of the mentor's time slots. If the booked attribute is null, or the time slot is available, add that time slot to the available array.
JSON.parse(response.body).each do |time_slot|
if time_slot["booked"].nil?
available << time_slot
end
end
# Return all of the available time slots.
available
end
end
|
describe SyntaxHighlighting::Captures do
let(:contents) do
{
"1" => {
"name" => "keyword.control.def.ruby"
},
"2" => {
"name" => "entity.name.function.ruby"
},
"3" => {
"name" => "punctuation.definition.parameters.ruby"
}
}
end
let(:described_instance) { described_class.new(contents) }
describe "#each" do
let(:iterations) do
[]
end
let(:blk) do
Proc.new do |key, value|
iterations << [key, value]
end
end
subject { described_instance.each(&blk) }
it "iterates all values" do
expect { subject }
.to change { iterations }
.from([])
.to(
[
[1, :"keyword.control.def.ruby"],
[2, :"entity.name.function.ruby"],
[3, :"punctuation.definition.parameters.ruby"]
]
)
end
end
describe "#[]" do
subject { described_instance[index] }
context "with an index that has a value" do
let(:index) { 2 }
it "returns the name" do
expect(subject).to eq(:"entity.name.function.ruby")
end
end
context "with an index that doesn't have a value" do
let(:index) { 4 }
it "returns nil" do
expect(subject).to eq(nil)
end
end
end
describe "#inspect" do
subject { described_instance.inspect }
it { is_expected.to be_a(String) }
end
describe "#to_s" do
subject { described_instance.to_s }
it { is_expected.to be_a(String) }
end
end
|
# Creates a temporary directory in the current working directory
# for temporary files created while running the specs. All specs
# should clean up any temporary files created so that the temp
# directory is empty when the process exits.
SPEC_TEMP_DIR = "#{File.expand_path(Dir.pwd)}/rubyspec_temp"
at_exit do
begin
Dir.delete SPEC_TEMP_DIR if File.directory? SPEC_TEMP_DIR
rescue SystemCallError
STDERR.puts <<-EOM
-----------------------------------------------------
The rubyspec temp directory is not empty.
Ensure that all specs are cleaning up temporary files.
Drectory: #{SPEC_TEMP_DIR}
-----------------------------------------------------
EOM
rescue Object => e
STDERR.puts "failed to remove spec temp directory"
STDERR.puts e.message
end
end
class Object
def tmp(name)
Dir.mkdir SPEC_TEMP_DIR unless File.exists? SPEC_TEMP_DIR
File.join SPEC_TEMP_DIR, name
end
end
|
# クラス
class Monster
def initialize(name)
@name = name
@hp = 100 + rand(100)
printf("%s appeared. His hp is %d!\n", @name, @hp)
end
def damage
@hp -= 10 + rand(10)
printf("%s's hp is now %d\n", @name, @hp)
printf("%s is now dead!\n", @name) if @hp < 0
end
def heal
@hp += 10 + rand(10)
printf("%s's hp is now %d\n", @name, @hp)
end
end
slime = Monster.new("slime")
slime.damage
slime.damage
|
# frozen_string_literal: true
require 'spec_helper'
describe OfflineSort::Sorter do
shared_examples "a correct offline sort" do
let(:count) { 10000 }
let(:entries_per_chunk) { 900 }
let(:enumerable) {}
let(:sort) {}
before do
@unsorted = enumerable.dup
r = Benchmark.measure do
result = OfflineSort.sort(enumerable, chunk_size: entries_per_chunk, &sort)
@sorted = result.map do |entry|
entry
end
end
puts r
end
it "produces the same sorted result as an in-memory sort" do
expect(@unsorted).to match_array(enumerable)
expect do
last = nil
entry_count = 0
@sorted.each do |entry|
if last.nil?
last = entry
entry_count += 1
next
end
raise "Out of order at line #{entry_count}" unless (sort.call(last) <=> sort.call(entry)) == -1
last = entry
entry_count += 1
end
end.not_to raise_error
expect(@sorted).to match_array(enumerable.sort_by(&sort))
end
end
let(:arrays) do
Array.new(count) do |index|
[SecureRandom.hex, index, SecureRandom.hex]
end
end
let(:array_sort_index) { 2 }
let(:array_sort) { Proc.new { |arr| arr[array_sort_index] } }
let(:hashes) do
Array.new(count) do |index|
{ 'a' => SecureRandom.hex, 'b' => index, 'c' => SecureRandom.hex }
end
end
let(:hash_sort_key) { 'c' }
let(:hash_sort) { Proc.new { |hash| hash[hash_sort_key] } }
context "with arrays" do
it_behaves_like "a correct offline sort" do
let(:enumerable) { arrays }
let(:sort) { array_sort }
end
context "with multiple sort keys" do
it_behaves_like "a correct offline sort" do
let(:enumerable) do
Array.new(count) do |index|
[index.round(-1), index, SecureRandom.hex]
end.shuffle
end
let(:sort) { Proc.new { |arr| [arr[0], arr[1]] } }
end
end
end
context "hashes" do
it_behaves_like "a correct offline sort" do
let(:enumerable) { hashes }
let(:sort) { hash_sort }
end
context "with multiple sort keys" do
it_behaves_like "a correct offline sort" do
let(:enumerable) do
Array.new(count) do |index|
{ 'a' => index.round(-1), 'b' => index, 'c' => SecureRandom.hex }
end.shuffle
end
let(:sort) { Proc.new { |hash| [hash['a'], hash['c']] } }
end
end
end
end
|
require 'active_support/concern'
module ProjectMediaCachedFields
extend ActiveSupport::Concern
# FIXME: Need to get this value from some API and update it periodically
def virality
0
end
module ClassMethods
def analysis_update(field)
[
{
model: DynamicAnnotation::Field,
if: proc { |f| f.field_name == field && f.annotation.annotation_type == 'verification_status' && !f.value.blank? },
affected_ids: proc { |f| [f.annotation.annotated_id] },
events: {
save: proc { |_pm, f| f.value }
}
},
{
model: DynamicAnnotation::Field,
if: proc { |f| f.field_name == 'metadata_value' },
affected_ids: proc { |f|
if ['Media', 'Link'].include?(f.annotation.annotated_type)
ProjectMedia.where(media_id: f.annotation.annotated_id).map(&:id)
end
},
events: {
save: :recalculate
}
}
]
end
end
included do
cached_field :linked_items_count,
start_as: 0,
update_es: true,
recalculate: proc { |pm| Relationship.where("source_id = ? OR target_id = ?", pm.id, pm.id).count },
update_on: [
{
model: Relationship,
affected_ids: proc { |r| [r.source_id, r.target_id] },
events: {
create: :recalculate,
destroy: :recalculate
}
}
]
cached_field :requests_count,
start_as: 0,
recalculate: proc { |pm| Dynamic.where(annotation_type: 'smooch', annotated_id: pm.id).count },
update_on: [
{
model: Dynamic,
if: proc { |d| d.annotation_type == 'smooch' },
affected_ids: proc { |d| [d.annotated_id] },
events: {
create: proc { |pm, _d| pm.requests_count + 1 },
destroy: proc { |pm, _d| pm.requests_count - 1 }
}
}
]
cached_field :demand,
start_as: 0,
update_es: true,
recalculate: proc { |pm|
n = 0
pm.related_items_ids.collect{ |id| n += ProjectMedia.find(id).requests_count }
n
},
update_on: [
{
model: Dynamic,
if: proc { |d| d.annotation_type == 'smooch' },
affected_ids: proc { |d| d.annotated.related_items_ids },
events: {
create: proc { |pm, _d| pm.demand + 1 }
}
},
{
model: Relationship,
affected_ids: proc { |r| [r.source&.related_items_ids, r.target_id].flatten.reject{ |id| id.blank? }.uniq },
events: {
create: :recalculate,
destroy: :recalculate
}
}
]
cached_field :last_seen,
start_as: proc { |pm| pm.created_at.to_i },
update_es: true,
recalculate: proc { |pm| (Dynamic.where(annotation_type: 'smooch', annotated_id: pm.related_items_ids).order('created_at DESC').first&.created_at || pm.reload.created_at).to_i },
update_on: [
{
model: Dynamic,
if: proc { |d| d.annotation_type == 'smooch' },
affected_ids: proc { |d| d.annotated&.related_items_ids.to_a },
events: {
create: proc { |_pm, d| d.created_at.to_i }
}
},
{
model: Relationship,
affected_ids: proc { |r| r.source&.related_items_ids.to_a },
events: {
create: proc { |_pm, r| [r.source&.last_seen.to_i, r.target&.last_seen.to_i].max },
destroy: :recalculate
}
}
]
cached_field :description,
recalculate: proc { |pm| !pm.analysis.dig('content').blank? ? pm.analysis.dig('content') : (pm.media&.metadata&.dig('description') || (pm.media.type == 'Claim' ? nil : pm.text)) },
update_on: analysis_update('content')
cached_field :title,
recalculate: proc { |pm| !pm.analysis.dig('title').blank? ? pm.analysis.dig('title') : (pm.media&.metadata&.dig('title') || pm.media.quote) },
update_on: analysis_update('title')
cached_field :status,
recalculate: proc { |pm| pm.last_verification_status },
update_on: [
{
model: DynamicAnnotation::Field,
if: proc { |f| f.field_name == 'verification_status_status' },
affected_ids: proc { |f| [f.annotation&.annotated_id.to_i] },
events: {
save: proc { |_pm, f| f.value }
}
}
]
cached_field :share_count,
start_as: 0,
update_es: true,
recalculate: proc { |pm| begin JSON.parse(pm.get_annotations('metrics').last.load.get_field_value('metrics_data'))['facebook']['share_count'] rescue 0 end },
update_on: [
{
model: DynamicAnnotation::Field,
if: proc { |f| f.field_name == 'metrics_data' },
affected_ids: proc { |f| [f.annotation&.annotated_id.to_i] },
events: {
save: :recalculate
}
}
]
end
end
|
class OtmAttraction < ApplicationRecord
# @@metro_url ||= 'https://collectionapi.metmuseum.org/public/collection/v1/search?q=hasImage=true'
# create rest response for it
# @@metro_response ||= RestClient.get(@@metro_url)
# turn that into JSON
# @@metro_images ||= JSON.parse(@@metro_response)
def self.otm_attractions_in_bounds(north,east,south,west)
# create otm url
otm_url = self.create_otm_url(north,east,south,west)
# get data from that url
otm_data = RestClient.get(otm_url)
p otm_data
# then parse it into JSON
JSON.parse(otm_data)
end
def self.create_otm_url(north,east,south,west)
# url = %Q(https://api.opentripmap.com/0.1/en/places/bbox?lon_min=#{west}&lon_max=#{east}&lat_min=#{south}&lat_max=#{north}&kinds=historical_places&src_attr=wikidata&apikey=#{ENV['OTM_API_KEY']})
url = 'https://api.opentripmap.com/0.1/en/places/bbox?lon_min=' + west.to_s + '&lon_max=' + east.to_s + '&lat_min=' + south.to_s + '&lat_max=' + north.to_s + '&kinds=historical_places&src_attr=wikidata&apikey=' + ENV['OTM_API_KEY']
end
def self.fetch_wikidata(xid)
url = 'https://api.opentripmap.com/0.1/en/places/xid/' + xid + '?apikey=' + ENV['OTM_API_KEY']
wikidata_data = RestClient.get(url)
# return data as json
wikidata_json = JSON.parse(wikidata_data)
p wikidata_json
return wikidata_json
end
end
|
class Api::V1::DocumentPolicy < ApplicationPolicy
def create?
return true
end
def create_pdf?
return true
end
class Scope < Scope
def resolve
scope.all
end
end
end
|
require 'rails_helper'
describe BackgroundImage do
location = "denver,co"
subject { BackgroundImage.new(location) }
it 'exists' do
expect(subject).to be_a(BackgroundImage)
end
context 'instance methods' do
context '#city_image' do
it 'returns a collection of image' do
expect(subject.city_image).to have_key(:city_id)
expect(subject.city_image).to have_key(:city_title)
expect(subject.city_image).to have_key(:city_url)
expect(subject.city_image).to have_key(:city_short_url)
end
end
end
end
|
require_relative '../utils/webpage'
class Twitter
include Cinch::Plugin
set :help, 'tw [status] - prints the status. Plugin also works automatically for Twitter URLs. Example: tw 297374318562779137'
match /twitter.com\/\w*\/status\/(\d+)/, use_prefix: false
match /tw(?:itter\.com)? +(\d+)$/
def execute(m, status_id)
m.reply status(status_id)
end
private
def status(status_id)
tweet = WebPage.load_json("https://api.twitter.com/1/statuses/show/#{status_id}.json")
"@#{tweet[:user][:screen_name]}: #{tweet[:text].gsub("\n", ' ')}"
end
end
|
require 'rails_helper'
describe 'Ship Messenger' do
describe '.post' do
context 'with valid params' do
it 'returns the slack response status 200' do
valid_ship_message_stub
team = create(:team, :with_user)
channel = create(:channel, :with_web_hook, team: team)
pull_request = create(:pull_request,
team: team,
user: team.users.first,
channel: channel)
code = ShipMessenger.post(pull_request)
expect(code).to eq('200')
end
end
context 'with invalid params' do
context 'like a missing web hook url' do
it 'returns nil' do
team = create(:team, :with_user)
channel = create(:channel, team: team)
pull_request = create(:pull_request,
team: team,
user: team.users.first,
channel: channel)
code = ShipMessenger.post(pull_request)
expect(code).to eq(nil)
end
end
context 'like a nil pull request' do
it 'returns nil' do
code = ShipMessenger.post(nil)
expect(code).to eq(nil)
end
end
end
end
end
|
class CreateMitTimesSections < ActiveRecord::Migration
def change
create_table :mit_times_sections do |t|
t.integer :section_id
t.integer :mit_time_id
end
end
end
|
class TwoSum
# attr_reader :nums :target
def initialize(nums, target)
@nums = nums
@target = target
end
def solution()
dict = Hash.new
@nums.each_with_index do |num, i|
if dict[@target - num]
return [dict[@target-num], i]
end
dict[num] = i
end
end
end
|
class Aboutmeimg < ActiveRecord::Base
attr_accessible :image, :user_id, :name
belongs_to :user
mount_uploader :image, AboutmeUploader
before_create :update_filename
#validates_uniqueness_of :name, :on => :create
private
def update_filename
self.name = image.file.filename
end
end
|
class Office < ActiveRecord::Base
def self.ordered_by_name
Office.all.order(:name)
end
end
|
ENV['RACK_ENV'] = 'test'
require_relative '../helpers/test_helper'
require_relative '../../lib/app'
class UserTest < Minitest::Test
include Rack::Test::Methods
def app
IdeaBoxApp
end
def setup
delete_test_db
end
def teardown
delete_test_db
end
def delete_test_db
File.delete('./ideabox_test') if File.exists?('./ideabox_test')
end
def post_a_user
post '/users', {:user => {:email => "bigTony@example.com"}}
end
def test_it_can_get_users_index
get '/users'
assert last_response.body.include?("Users")
end
def test_it_can_post_a_user
post_a_user
assert last_response.redirect?
follow_redirect!
assert last_response.body.include?("bigTony@example.com"), "after posting user, redirect back to user index"
end
def test_it_can_get_a_user_show_page
post_a_user
get '/users/2'
assert last_response.ok?, "users/2 should respond with ok"
assert last_response.body.include?("user page"), "user show page should include 'user page'"
assert last_response.body.include?("bigTony@example.com"), "user show page should show the user's email"
end
def test_it_can_post_a_new_idea_from_user_show_page
# depracated - needs to pass in a group_id of a group that belongs to this
# user
skip
post_a_user
post '/users/2', {:idea => {:title => "user 2 idea title", :description => "idea desc", :user_id => 2}}
assert last_response.redirect?, "after posting idea, should redirect"
follow_redirect!
assert last_response.body.include?("bigTony@example.com"), "page should show user's email"
assert last_response.body.include?("user 2 idea title"), "page should show new idea title"
end
def make_ideas_with_tags(amount)
titles = ["big idea", "foofoo", "big dingo"]
tags = ["foo", "foo", "bar"]
for i in 0..(amount-1) do
count = i
IdeaStore.create("title" => titles[i],
"description" => "social network for penguins",
"rank" => 3,
"user_id" => 1,
"group_id" => 1,
"tags" => tags[i])
count += 1
end
end
def test_it_returns_all_tags
make_ideas_with_tags(3)
user = UserStore.find(1)
assert_equal ["foo", "bar"], user.all_tags
end
end
|
class ResourceType < ActiveRecord::Base
validates_presence_of :description, :points
has_many :resources
end
|
class CreateGolves < ActiveRecord::Migration
def change
create_table :golves do |t|
t.integer :attendee_id
t.integer :tournament_id
t.integer :stroke_id
t.integer :stroke_score
t.timestamps
end
end
end
|
class RemoveColumnsToApplicantActivities < ActiveRecord::Migration
def change
remove_column :applicant_activities, :past_status
remove_column :applicant_activities, :current_status
remove_column :applicant_activities, :body
remove_column :applicant_activities, :subject
end
end
|
require_relative 'linked_list'
# Write code to partition a linked list around a value x,
# such that all nodes less than x come before all nodes
# greater than or equal to x. If x is contained within the
# list, the values of x only need to be after the elements
# less than x (see below). The partition element x can appear
# anywhere in the "right partition"; it does not need to
# appear between the left and right partitions.
#EXAMPLE
# Input: 3 -> 5 -> 8 -> 5 -> 10 -> 2 -> 1[partition=5]
# Output: 3 -> 1 -> 2 -> 10 -> 5 -> 5 -> 8
# naive approach
# O(n) time complexity
# O(n) space complexity
def partition(lk, x)
node = lk
less = []
greater = []
while !node.nil?
if node.data < x
less << node.data
else
greater << node.data
end
node = node.next
end
result = NodeList.new(less[0])
less[1..-1].each do |n|
result.append(n)
end
greater.each do |n|
result.append(n)
end
result
end
# O(n) time complexity
# O(1) space complexity
def partition1(lk, x)
p1 = lk
p2 = p1.next
while !p2.nil?
if p1.data >= x && p2.data >= x
p2 = p2.next
elsif p1.data >= x && p2.data < x
temp = p2.data
p2.data = p1.data
p1.data = temp
p2 = p2.next
p1 = p1.next
else
p2 = p2.next
p1 = p1.next
end
end
lk
end
lk = NodeList.new(3)
lk.append(5)
lk.append(8)
lk.append(5)
lk.append(10)
lk.append(2)
lk.append(1)
puts lk
puts partition1(lk, 5)
|
class AddProcessedToApps < ActiveRecord::Migration
def change
add_column :apps, :processed, :boolean
end
end
|
module EmbeddableContent
class EmbeddedTagInfo
attr_reader :record, :embedded_model, :attr, :dom_node
def initialize(record, embedded_model, attr, dom_node)
@record = record
@embedded_model = embedded_model
@attr = attr
@dom_node = dom_node
end
def available?
match.present?
end
def embedded_record_id
match.try :first
end
def embedded_record_ext
match.try :last
end
def embedded_record
@embedded_record ||= embedded_model.find embedded_record_id
end
private
def src
@src ||= dom_node.attributes['src'].to_html
end
def embed_src_path
embedded_model.model_name.route_key
end
def match
@match ||= src.match(%r{\/#{embed_src_path}\/(\d+)\.(\w+)}).try :captures
end
def document
@document ||= Nokogiri::HTML.fragment searchable_text
end
def searchable_text
record[attr].is_a?(Array) ? record[attr].join(' ') : record[attr]
end
end
end
|
#
# Cookbook Name:: stackdriver
# Recipe:: repo
# License:: MIT License
#
# Copyright 2013, StackDriver
#
# All rights reserved
#
# Re-make the yum cache vi command resource
execute "create-yum-cache" do
command "yum -q makecache"
action :nothing
end
# Reload the yum cache using the Chef provider
ruby_block "internal-yum-cache-reload" do
block do
Chef::Provider::Package::Yum::YumCache.instance.reload
end
action :nothing
end
# Create the StackDriver yum repo file in yum.repos.d
cookbook_file "/etc/yum.repos.d/stackdriver.repo" do
source "stackdriver.repo"
mode 00644
notifies :run, "execute[create-yum-cache]", :immediately
notifies :create, "ruby_block[internal-yum-cache-reload]", :immediately
end
|
module UserRepository
extend ActiveSupport::Concern
include BaseRepository
included do
scope :active, where(state: :active)
end
end
|
class ChangeDefaultValueToCreatedAtAndUpdatedAtByNow < ActiveRecord::Migration[5.2]
def change
change_column_default :media, :created_at, -> { 'CURRENT_TIMESTAMP' }
change_column_default :media, :updated_at, -> { 'CURRENT_TIMESTAMP' }
end
end
|
require 'spec_helper'
describe 'simp_openldap::server::limits' do
context 'supported operating systems' do
on_supported_os.each do |os, os_facts|
context "on #{os}" do
let(:pre_condition) {
'class { "simp_openldap": is_server => true }'
}
let(:facts) do
os_facts
end
if os_facts.dig(:os,:release,:major) >= '8'
it { skip("does not support #{os}") }
next
end
let(:title) { '111' }
let(:params) {{
:who => 'on_first',
:limits => ['foo','bar','baz']
}}
it { is_expected.to compile.with_all_deps }
it { is_expected.to create_simp_openldap__server__dynamic_include("limit_#{title}").with_content(
/limits #{params[:who]} #{params[:limits].join(' ')}/
)}
end
end
end
end
|
require 'rails_helper'
RSpec.describe Delayed::Backend::ActiveRecord::Job, regressor: true do
# === Relations ===
# === Nested Attributes ===
# === Database (Columns) ===
it { is_expected.to have_db_column :id }
it { is_expected.to have_db_column :priority }
it { is_expected.to have_db_column :attempts }
it { is_expected.to have_db_column :handler }
it { is_expected.to have_db_column :last_error }
it { is_expected.to have_db_column :run_at }
it { is_expected.to have_db_column :locked_at }
it { is_expected.to have_db_column :failed_at }
it { is_expected.to have_db_column :locked_by }
it { is_expected.to have_db_column :queue }
it { is_expected.to have_db_column :created_at }
it { is_expected.to have_db_column :updated_at }
# === Database (Indexes) ===
# === Validations (Length) ===
# === Validations (Presence) ===
# === Validations (Numericality) ===
# === Enums ===
end
|
name =("Ricky")
say_hello do
# I call on the method, say_hello, and give it the string "Ricky"
say_hello("Ricky")
# The method prints this text to the screen:
Hello Ricky!
end
|
require "faraday"
require "commit-live/endpoint"
module CommitLive
class API
attr_reader :conn
def initialize(api_url = nil)
endpoint = api_url || CommitLive::Endpoint.new.get()
@conn = Faraday.new(url: endpoint) do |faraday|
faraday.adapter Faraday.default_adapter
end
end
def get(url, options = {})
request :get, url, options
end
def post(url, options = {})
request :post, url, options
end
private
def request(method, url, options = {})
begin
connection = options[:client] || @conn
connection.send(method) do |req|
req.url url
buildRequest(req, options)
end
rescue Faraday::ConnectionFailed
puts "Connection error. Please try again."
end
end
def buildRequest(request, options)
buildHeaders(request, options[:headers])
buildParams(request, options[:params])
buildBody(request, options[:body])
end
def buildHeaders(request, headers)
if headers
headers.each do |header, value|
request.headers[header] = value
end
end
end
def buildParams(request, params)
if params
params.each do |param, value|
request.params[param] = value
end
end
end
def buildBody(request, body)
if body
request.body = Oj.dump(body, mode: :compat)
end
end
end
end
|
class CreatePosters < ActiveRecord::Migration[5.2]
def change
create_table :posters do |t|
t.string :lat
t.string :long
t.integer :pet_id
t.string :pet_description
t.string :poster_name
t.string :poster_phone
t.timestamps
end
end
end
|
#demonstrates how super (without args) sends to the corresponding superclass method
#the arguments passed to the subclass method in which super is declared.
class Bicycle
attr_reader :gears, :wheels, :seats
def initialize(gears = 1)
@wheels = 2
@seats = 1
@gears = gears
end
end
class Tandem < Bicycle
def initialize(gears)
super
@seats = 2
end
end
t = Tandem.new(2)
puts t.gears
puts t.wheels
puts t.seats
b = Bicycle.new
puts b.gears
puts b.wheels
puts b.seats
|
# -*- mode: ruby -*-
# vi: set ft=ruby :
Vagrant.configure("2") do |config|
config.vm.box = "ubuntu1204"
config.vm.box_url = "https://opscode-vm.s3.amazonaws.com/vagrant/opscode_ubuntu-12.04_provisionerless.box"
# install latest Chef client and add the node recipe
config.omnibus.chef_version = "11.4.4"
config.vm.provision :chef_solo do |chef|
chef.add_recipe "currency-market"
end
end
|
# Build a tic-tac-toe game on the command line where two human players can play against each other
# and the board is displayed in between turns.
# Simple game loop for two players.
class Game
def play_game(current_board)
player_symbol = 'X'
until current_board.confirm_win
player_symbol = if player_symbol == 'X'
'O'
else
'X'
end
puts "Player #{player_symbol} enter position:"
current_board.make_move(gets.chomp, player_symbol)
break if current_board.complete?
end
if current_board.complete?
puts "You're both losers."
else
puts "Player #{player_symbol} wins!"
end
end
end
# Simple console display board with simple numpad position selection and input enforcement.
class Board
def initialize
@board11 = '7'
@board12 = '8'
@board13 = '9'
@board21 = '4'
@board22 = '5'
@board23 = '6'
@board31 = '1'
@board32 = '2'
@board33 = '3'
@valid_moves = %w[1 2 3 4 5 6 7 8 9]
end
def show_board
print "\n #{@board11}|#{@board12} |#{@board13}\n__ __ __
\n #{@board21}|#{@board22} |#{@board23}\n__ __ __
\n #{@board31}|#{@board32} |#{@board33}\n\n\n"
end
def invalid?(attempted_position)
!@valid_moves.include?(attempted_position)
end
def complete?
@valid_moves.empty?
end
def make_move(position, player)
if invalid?(position)
puts 'Invalid position. Enter invalid position:'
make_move(gets.chomp, player)
else
@valid_moves.delete(position)
@board11 = player if position == '7'
@board12 = player if position == '8'
@board13 = player if position == '9'
@board21 = player if position == '4'
@board22 = player if position == '5'
@board23 = player if position == '6'
@board31 = player if position == '1'
@board32 = player if position == '2'
@board33 = player if position == '3'
show_board
end
end
def confirm_win
if (@board11 == @board12) && (@board12 == @board13)
true
elsif (@board21 == @board22) && (@board22 == @board23)
true
elsif (@board31 == @board32) && (@board32 == @board33)
true
elsif (@board11 == @board21) && (@board21 == @board31)
true
elsif (@board12 == @board22) && (@board22 == @board32)
true
elsif (@board13 == @board23) && (@board23 == @board33)
true
elsif (@board11 == @board22) && (@board22 == @board33)
true
elsif (@board13 == @board22) && (@board22 == @board31)
true
else
false
end
end
end
board = Board.new
board.show_board
game = Game.new
game.play_game(board)
|
class ChangeDataTypeEmployeeNumber < ActiveRecord::Migration
def change
change_column :employees, :employee_number, 'integer USING CAST(employee_number AS integer)'
end
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.