text stringlengths 10 2.61M |
|---|
number_of_monkeys = ["ten", "nine", "eight", "seven", "six", "five", "four", "three", "two", "one"]
# puts '-' * 10
number_of_monkeys.each do |monkey|
puts "#{monkey} little monkeys jumping on the bed,
One fell off and bumped his head,
Mama called the doctor and the doctor said,
No more monkeys jumping on the bed!"
end
|
class ChangeIsbnToString < ActiveRecord::Migration[5.1]
def change
change_column :desidered_books, :ISBN, :string, :limit => 13
change_column :proposed_books, :ISBN, :string, :limit => 13
end
end
|
class UsersController < ApplicationController
def new
if current_user.present?
redirect_to calendar_path
return
end
expires_in 15.minutes, public: true
end
def create
self.current_user = User.from_omniauth(auth_hash)
redirect_to calendar_path
end
private
def auth_hash
request.env['omniauth.auth']
end
end
|
require 'cells_helper'
RSpec.describe AdminArea::CardRecommendations::Cell::Table do
controller ApplicationController
let(:person) { create_account(:eligible, :onboarded).owner }
let(:recs) { Array.new(3) { create_rec(person: person) } }
def render_for(recs, options = {})
cell(described_class, recs, options).()
end
example '' do
rendered = render_for(recs)
recs.each do |rec|
expect(rendered).to have_selector "#card_recommendation_#{rec.id}"
end
expect(rendered).not_to have_content person.first_name
end
example 'with_person_column: true' do
rendered = render_for(recs, with_person_column: true)
recs.each do |rec|
row = rendered.find("#card_recommendation_#{rec.id}")
expect(row).to have_content person.first_name
end
end
end
|
# typed: false
class V1::GamesController < ApplicationController
def index
render json: Game.all
end
def create
new_game = Game.create(game_params)
redirect_to v1_game_path(new_game)
end
def show
render json: Game.find(params[:id])
end
private
def game_params
params.require(:game).permit(:name)
end
end
|
class Tag < ApplicationRecord
has_many :question_tags
has_many :questions, through: :question_tags
end
|
module AttrAbility
class Railtie < Rails::Railtie
initializer "attr_ability.model_additions" do |app|
require "attr_ability/model_additions"
ActiveSupport.on_load :active_record do
include AttrAbility::ModelAdditions
end
end
initializer "attr_ability.controller_additions" do |app|
require 'attr_ability/controller_additions'
ActiveSupport.on_load :action_controller do
extend AttrAbility::ControllerAdditions
end
end
end
end
|
# frozen_string_literal: true
class Token < ApplicationRecord
before_create :generate_access_token
before_create :set_expiration
belongs_to :user
def expired?
Time.current >= expires_at
end
private
def generate_access_token
begin
self.access_token = SecureRandom.hex
end while self.class.exists?(access_token: access_token)
end
def set_expiration
self.expires_at = Time.current + 30.days
end
end
|
Meowmates::Application.routes.draw do
root to: 'home#index'
devise_for :user
# Standard GET routing.
get "home/index"
get 'home/get_email' => 'home#get_email'
get "home/show" => "home#show"
get "home/login" => "home#login"
get "animal/get_animals" => "animal#get_animals"
# Mailboxer
resources :messages
resources :conversations
# resources :conversations, only: [:index, :show, :new, :create] do
# member do
# post :reply
# post :trash
# post :untrash
# end
# end
resources :home do
member do
post :new
post :reply
post :trash
post :untrash
end
end
resources :messages do
member do
post :new
end
end
resources :conversations do
member do
post :reply
post :trash
post :untrash
end
collection do
get :trashbin
post :empty_trash
end
end
resources :animal, :profile
end
|
class Net::ICAPRequest
include Net::HTTPHeader
def initialize(method, resbody, uri, initheader = nil)
@method = method
@response_has_body = resbody
@body = nil
case uri
when URI
@uri = uri.dup
when String
@uri = URI(uri)
end
host = @uri.hostname
initialize_http_header initheader
self['Host'] ||= host
self['User-Agent'] ||= 'Ruby'
end
attr_reader :method
attr_reader :uri
attr_accessor :body
def response_body_permitted?
@response_has_body
end
def exec(sock)
if @uri
if @uri.port == @uri.default_port
self['host'] = @uri.host
else
self['host'] = "#{@uri.host}:#{@uri.port}"
end
end
if @body
if preview
send_request_with_preview sock, @body
else
send_request_with_body sock, @body
end
else
write_header sock
end
end
def preview
return nil unless key?('Preview')
preview = self['Preview'].slice(/\d+/) or
raise Net::ICAPHeaderSyntaxError, 'wrong Preview format'
preview.to_i
end
def update_uri(host, port)
@uri.host ||= host
@uri.port = port
@uri
end
private
class Chunker #:nodoc:
def initialize(sock)
@sock = sock
@prev = nil
end
def write(buf)
# avoid memcpy() of buf, buf can huge and eat memory bandwidth
@sock.write("#{buf.bytesize.to_s(16)}\r\n")
rv = @sock.write(buf)
@sock.write("\r\n")
rv
end
def finish
@sock.write("0\r\n\r\n")
end
end
def send_request_with_body(sock, body)
write_header(sock)
chunker = Chunker.new(sock)
chunker.write(body)
chunker.finish
end
def send_request_with_preview(sock, body)
write_header(sock)
chunker = Chunker.new(sock)
chunker.write(body[0,preview])
chunker.finish
res = wait_for_continue(sock)
chunker.write(body[preview, body.length-preview])
chunker.finish
end
def wait_for_continue(sock)
res = nil
if sock.respond_to?(:continue_timeout)
timeout = sock.continue_timeout
else
timeout = 30
end
if IO.select([sock.io], nil, nil, timeout)
res = Net::ICAPResponse.read_new(sock)
unless res.kind_of?(Net::ICAPContinue)
throw :response, res
end
end
res
end
def write_header(socket)
buf = "#{@method} #{@uri} ICAP/1.0\r\n"
each_capitalized do |key, value|
buf << "#{key}: #{value}\r\n"
end
buf << "\r\n"
socket.write buf
end
end
class Net::ICAP::Options < Net::ICAPRequest
def initialize(uri, initheader = nil)
super('OPTIONS', false, uri, initheader)
end
end
class Net::ICAP::Respmod < Net::ICAPRequest
def initialize(uri, initheader = nil)
super('RESPMOD', true, uri, initheader)
end
end
class Net::ICAP::Reqmod < Net::ICAPRequest
def initialize(uri, initheader = nil)
super('REQMOD', true, uri, initheader)
end
end
|
Civiccommons::Application.routes.draw do
# ----------------------------------------
# ROUTES README
# ----------------------------------------
# * In general routes go from most-to-least specific, top-to-bottom
# * We use resource routes for all standard routes, including:
# :get => [:index, :show, :new, :edit], :post => :create, :put => :update, and :delete => :destroy
# * We use the :only or :except clauses to exclude all standard routes not in use
# e.g. resources :some_controller, only: [:index, :show]
# * We do not use custom routes to explicitly declare standard routes
# * We group all custom routes based on the controller
# * We put resource routes and generic pattern-matching routes after custom routes
# e.g. '/some_controller/:id' goes below '/some_controller/some_name'
# * We use consistent syntax for route mapping
# e.g. get '/blah', to: 'bleep#bloop' instead of map '/blah', :to => 'bleep#bloop', :via => :get if possible
#Application Root
root to: "homepage#show"
#Custom Matchers
#Contributions
post '/contributions/create_confirmed_contribution', to: 'contributions#create_confirmed_contribution', as: 'create_confirmed_contribution'
delete '/contributions/moderate/:id', to: 'contributions#moderate_contribution', as: 'moderate_contribution'
delete '/contributions/:id', to: 'contributions#destroy', as: 'contribution'
#Conversations
match '/conversations/preview_node_contribution', to: 'conversations#preview_node_contribution'
get '/conversations/node_conversation', to: 'conversations#node_conversation'
get '/conversations/new_node_contribution', to: 'conversations#new_node_contribution'
get '/conversations/edit_node_contribution', to: 'conversations#edit_node_contribution'
get '/conversations/node_permalink/:id', to: 'conversations#node_permalink'
put '/conversations/update_node_contribution', to: 'conversations#update_node_contribution'
put '/conversations/confirm_node_contribution', to: 'conversations#confirm_node_contribution'
get '/conversations/responsibilities', to: 'conversations#responsibilities', as: 'conversation_responsibilities'
#Subscriptions
post '/subscriptions/subscribe', to: 'subscriptions#subscribe'
post '/subscriptions/unsubscribe', to: 'subscriptions#unsubscribe'
#UnsubscribeDigest
get '/unsubscribe-me/:id', to: 'unsubscribe_digest#unsubscribe_me', as: 'unsubscribe_confirmation'
put '/unsubscribe-me/:id', to: 'unsubscribe_digest#remove_from_digest'
#Community
get '/community', to: 'community#index', as: 'community'
#Widget
get '/widget', to: 'widget#index'
#Static Pages
get '/about', to: 'static_pages#about'
get '/blog', to: 'static_pages#blog', as: 'blog'
get '/build_the_commons', to: 'static_pages#build_the_commons'
get '/contact_us', to: 'static_pages#contact'
get '/faq', to: 'static_pages#faq'
get '/partners', to: 'static_pages#partners'
get '/poster', to: 'static_pages#poster'
get '/posters', to: 'static_pages#poster'
get '/press', to: 'static_pages#in_the_news'
get '/principles', to: 'static_pages#principles'
get '/team', to: 'static_pages#team'
get '/terms', to: 'static_pages#terms'
get '/jobs', to: 'static_pages#jobs'
get '/careers', to: 'static_pages#jobs'
#Devise Routes
devise_for :people,
:controllers => { :registrations => 'registrations', :confirmations => 'confirmations', :sessions => 'sessions' },
:path_names => { :sign_in => 'login', :sign_out => 'logout', :password => 'secret', :confirmation => 'verification', :registration => 'register', :sign_up => 'new' }
devise_scope :person do
match '/people/ajax_login', :to=>'sessions#ajax_create', :via=>[:post]
end
#Sort and Filters
constraints FilterConstraint do
get 'conversations/:filter', to: 'conversations#filter', as: 'conversations_filter'
end
#Resource Declared Routes
#Declare genericly-matched GET routes after Filters
resources :user, only: [:show, :update, :edit] do
delete "destroy_avatar", on: :member
end
resources :issues, only: [:index, :show] do
post 'create_contribution', on: :member
end
resources :conversations, only: [:index, :show, :new, :create]
resources :regions, only: [:index, :show]
resources :links, only: [:new, :create]
resources :invites, only: [:new, :create]
#Namespaces
namespace "admin" do
root to: "dashboard#show"
resources :articles
resources :conversations
resources :issues
resources :regions
resources :people do
get 'proxies', on: :collection
put 'lock_access', on: :member
put 'unlock_access', on: :member
end
end
namespace "api" do
get '/:id/conversations', to: 'conversations#index', format: :json
get '/:id/issues', to: 'issues#index', format: :json
get '/:id/contributions', to: 'contributions#index', format: :json
get '/:id/subscriptions', to: 'subscriptions#index', format: :json
end
end
|
FactoryBot.define do
factory :locale do
name = "Bad Detention Dudes"
degree = 1
location = "123 fake st"
citation = "www.google.com"
contact = "a@b.c"
connections = 3
blurb = "it's a very bad place"
end
end |
class Subject
def initialize
@observers = []
end
def add_observers(observer)
@observers << observer
end
def delete_observer(observer)
@observers.delete(observer)
end
def notify_observers
@observers.each do |observer|
observer.update(self)
end
end
end
class Employee < Subject
attr_reader :name, :address
attr_reader :salary
def initialize(name, title, salary)
super()
@name = name
@salary = salary
@address = address
end
def salary=(new_salary)
@salary = new_salary
notify_observers
end
end
# Ruby only allows a class to have one subclass!
# Solution: use a module
|
class AddSearchTermsToTrack < ActiveRecord::Migration
def self.up
add_column :tracks, :referrer_host, :string, :limit => 100
add_column :tracks, :search_terms, :string
add_column :tracks, :traffic_source, :string, :limit => 10
end
def self.down
remove_column :tracks, :traffic_source
remove_column :tracks, :search_terms
remove_column :tracks, :referrer_host
end
end
|
class MarkReader
if Rails.env.production?
FILE_PATH = "#{Rails.root}/bookmarks.txt"
else
FILE_PATH = "#{Rails.root}/public/bookmarks.txt"
end
attr_reader :marks
def initialize
@marks = parse_file
end
def [](category)
marks[category]
end
def update!(new_mark)
marks.merge!(new_mark)
write_changes_to_file
end
private
def parse_file
return {} unless File.file?(FILE_PATH)
marks = File.readlines(FILE_PATH).map(&:chomp)
marks.each_with_object({}) do |unparsed_line, state|
category, mark = unparsed_line.split(" ")
state[category] = mark.to_i
end
end
def write_changes_to_file
File.open(FILE_PATH, "w") do |f|
marks.each do |category, counter|
f.puts "#{category} #{counter}"
end
end
nil
end
end |
json.array!(@caterers) do |caterer|
json.extract! caterer, :id, :name
json.url caterer_url(caterer, format: :json)
end
|
class Summary < ApplicationRecord
validates :text, presence: true
belongs_to :user
belongs_to :theme
end
|
class Category < ApplicationRecord
enum status: [:active, :inactive]
scope :active, -> {where(status: 0)}
validates :name, uniqueness: true, presence: true
validates :status, presence: true
end
|
require 'spec_helper'
describe Gpdb::ConnectionChecker do
let(:gpdb_instance) { FactoryGirl.build(:gpdb_instance) }
let(:account) { FactoryGirl.build(:instance_account) }
it "requires that a real connection to GPDB can be established" do
stub(Gpdb::ConnectionBuilder).connect! { raise(ActiveRecord::JDBCError.new("connection error")) }
expect { Gpdb::ConnectionChecker.check!(gpdb_instance, account) }.to raise_error(ApiValidationError) { |error|
error.record.errors.get(:connection).should == [[:generic, {:message => "connection error"}]]
}
end
it "sets the instance's status to be 'online''" do
stub(Gpdb::ConnectionBuilder).connect!
Gpdb::ConnectionChecker.check!(gpdb_instance, account)
gpdb_instance.state.should == "online"
end
it "check the validation of account attributes, before checking connection" do
account.db_username = nil
expect { Gpdb::ConnectionChecker.check!(gpdb_instance, account) }.to raise_error ActiveRecord::RecordInvalid
end
it "check the validation of instance attributes, before checking connection" do
gpdb_instance.port = nil
expect { Gpdb::ConnectionChecker.check!(gpdb_instance, account) }.to raise_error ActiveRecord::RecordInvalid
end
end |
# name: discourse-delete-user-by-email
# about: Support delete user from group by using user email
# version: 0.3
# authors: Ming
# url: https://github.com/ming-relax/discourse-delete-user-by-email
after_initialize do
class ::GroupsController
def remove_member
group = Group.find(params[:id])
guardian.ensure_can_edit!(group)
if params[:user_id].present?
user = User.find(params[:user_id])
elsif params[:username].present?
user = User.find_by_username(params[:username])
elsif params[:user_email].present?
user = User.find_by_email(params[:user_email])
else
raise Discourse::InvalidParameters.new('user_id or username or user_email must be present')
end
user.primary_group_id = nil if user.primary_group_id == group.id
group.users.delete(user.id)
if group.save && user.save
render json: success_json
else
render_json_error(group)
end
end
end
end
|
module RestoreAgent::Object
class File < Base
def file_path
if parent.type == 'Filesystem'
::File.join(parent.mount_point, name)
else
::File.join(parent.file_path, name)
end
end
def scan(snapper, included)
event = nil
st = ::File.lstat(self.file_path)
unless attrs = snapper.object_db[self.path]
# file not in the db. add it.
attrs = {
:mtime => st.mtime,
:mode => st.mode
}
event = 'A'
else
# file was in the db before. check mod time, etc
#if st.mtime > attrs[:mtime] || st.mode != attrs[:mode]
attrs = {
:mtime => st.mtime,
:mode => st.mode
}
event = 'M'
#end
end
if event
puts "#{event} #{self.path}"
# ask the snapper object to send the needed data back to the master.
# all we need to provide is the event, our object path, and an IO object
# to the data.
begin
f = ::File.new(self.file_path, "r")
rescue => e
puts e.to_s
ensure
begin
snapper.update_data(self.path, event, container?, {}, f)
rescue => e
puts e.to_s
ensure
f.close if f
end
end
#snapper.object_db[self.path] = attrs
return true
end
return false
end
end
end |
require 'set'
module Valet
class Options < Set
def [](name)
find_option(name)
end
def method_missing(method_name, *args, &block)
if (option = find_switch(method_name)) || (option = find_flag(method_name))
option.value
else
super
end
end
private
def find_option(name)
self.find { |option| name == option.name }
end
def find_switch(name)
self.find { |option| name =~ /#{option.name}\?/ if option.switch? }
end
def find_flag(name)
self.find { |option| name == option.name if option.flag? }
end
end
end
|
require 'rails_helper'
require 'test_helper'
# def test_image
# Rack::Test::UploadedFile.new(Rails.root.join('spec/images/paintedicon.jpeg'), 'image/jpg')
# end
describe Category do
let(:category) { Category.create(title: 'Test', image: test_image) }
describe '#tag_names=' do
describe 'no tags' do
it 'does nothing' do
expect { category.tag_names = ''}.not_to raise_error
end
end
end
describe 'one tag that does not exist' do
it 'adds a tag to the category' do
category.tag_names = 'yolo'
expect(category.tags.length).to eq 1
end
end
describe 'two tags that do not exist' do
it 'adds a tag to the category' do
category.tag_names = 'yolo, swag'
expect(category.tags.length).to eq 2
end
end
describe 'tag already exists' do
let!(:existing_tag){Tag.create(name: 'yolo')}
it 'reuses the existing tag' do
category.tag_names = 'yolo'
expect{ category.save! }.not_to raise_error
expect(category.tags).to include existing_tag
expect(Tag.count).to eq 1
end
end
end
|
require 'rails_helper'
RSpec.describe Message, type: :model do
before { @message = build(:message) }
subject { @message }
it { should respond_to(:body) }
it { should respond_to(:user_id) }
it { should respond_to(:chat_room_id) }
it { should be_valid }
describe 'when body is not present' do
before { @message.body = ' ' }
it { should_not be_valid }
end
describe 'when body is too long' do
before { @message.body = 'a' * 2001 }
it { should_not be_valid }
end
describe 'when body is too short' do
before { @message.body = 'a' }
it { should_not be_valid }
end
describe 'when user reference is not present' do
before { @message.user = nil }
it { should_not be_valid }
end
describe 'when chat room reference is not present' do
before { @message.chat_room = nil }
it { should_not be_valid }
end
end
|
class CreateUsdExchangeRates < ActiveRecord::Migration[5.2]
def change
create_table :usd_exchange_rates do |t|
t.float :rate, null: false
t.boolean :is_forced
t.datetime :expiration_date
t.timestamps
end
end
end
|
class ChangeUserGoldService < ArchService::ServiceObject
def self.body(user:, gold_change:)
new_amount = user.gold + gold_change
fail("You don't have enough gold!") if new_amount < 0
user.update_attribute("gold", new_amount)
respond(message: "Gold changed!", success: true)
end
end |
#!/usr/bin/env ruby
# encoding: utf-8
# You might want to change this
ENV["RAILS_ENV"] ||= "develpment"
root = File.expand_path(File.dirname(__FILE__))
root = File.dirname(root) until File.exists?(File.join(root, 'config'))
Dir.chdir(root)
require File.join(root, "config", "environment")
$running = true
begin
$arduino = Arduino.new
rescue Exception => e
puts "[ERROR] #{e.message}"
$running = false
end
Signal.trap("TERM") do
$arduino.close
$running = false
end
while($running) do
redis_pending = $REDIS.hgetall('sensors_pending')
unless redis_pending.empty?
redis_pending.each do |code, value|
$arduino.write("#{code}:#{value}.")
puts "[DEBUG] SENT TO ARDUINO: #{code}:#{value}."
$REDIS.hdel('sensors_pending', code)
sleep 0.3
end
end
arduino_return = $arduino.read
if arduino_return
puts "[DEBUG] RECEIVED FROM ARDUINO: #{arduino_return}"
arduino_return = arduino_return.split(":")
sensors = Sensor.where(:arduino_code => arduino_return[0])
if sensors.empty?
case arduino_return[0]
when I18n.t('main_alarm.arduino_code')
extra_params = "?"
alert = Alert.new(:style => "main_alarm")
case arduino_return[1]
when "0"
alert.style = "notice"
alert.description = I18n.t('main_alarm.descriptions.turned_off')
extra_params += "main_alarm_off=true"
Alert.turn_off_main_alarm
alert.save
uri = URI.parse("http://#{I18n.t('config.server_host')}:#{I18n.t('config.server_port')}/alerts/#{alert.id}/arduino_render#{extra_params}")
Net::HTTP.post_form(uri, initheader = {'Content-Type' =>'application/json'})
alert.spam_notifications(:debug => true)
when "1"
alert.description = I18n.t('main_alarm.descriptions.fire')
alert.save
uri = URI.parse("http://#{I18n.t('config.server_host')}:#{I18n.t('config.server_port')}/alerts/#{alert.id}/arduino_render#{extra_params}")
Net::HTTP.post_form(uri, initheader = {'Content-Type' =>'application/json'})
alert.spam_notifications(:debug => true)
when "2"
alert.description = I18n.t('main_alarm.descriptions.intrusion')
alert.save
uri = URI.parse("http://#{I18n.t('config.server_host')}:#{I18n.t('config.server_port')}/alerts/#{alert.id}/arduino_render#{extra_params}")
Net::HTTP.post_form(uri, initheader = {'Content-Type' =>'application/json'})
alert.spam_notifications(:debug => true)
when "3"
alert.description = I18n.t('main_alarm.descriptions.temperature', :value => arduino_return[2])
alert.save
uri = URI.parse("http://#{I18n.t('config.server_host')}:#{I18n.t('config.server_port')}/alerts/#{alert.id}/arduino_render#{extra_params}")
Net::HTTP.post_form(uri, initheader = {'Content-Type' =>'application/json'})
alert.spam_notifications(:debug => true)
when "4"
alert.style = "warning"
alert.description = I18n.t('main_alarm.descriptions.children_room_movement')
alert.save
uri = URI.parse("http://#{I18n.t('config.server_host')}:#{I18n.t('config.server_port')}/alerts/#{alert.id}/arduino_render#{extra_params}")
Net::HTTP.post_form(uri, initheader = {'Content-Type' =>'application/json'})
end
when "iniciado"
send_on_start_sensors = Sensor.send_on_start
unless send_on_start_sensors.empty?
for sensor in send_on_start_sensors
$arduino.write("#{sensor.arduino_code}:#{sensor.value}.")
puts "[DEBUG] SENT TO ARDUINO: #{sensor.arduino_code}:#{sensor.value}."
sleep 0.3
end
end
else
puts "[WARNING] SENSOR NOT FOUND IN DB: #{arduino_return[0]}"
end
else
for sensor in sensors
if sensor.edit_by_arduino?
sensor.value = arduino_return[1]
sensor.arduino_value = arduino_return[2] unless arduino_return[2].blank?
sensor.save
uri = URI.parse("http://#{I18n.t('config.server_host')}:#{I18n.t('config.server_port')}/sensors/#{sensor.id}/arduino_render")
Net::HTTP.post_form(uri, initheader = {'Content-Type' =>'application/json'})
end
end
end
end
end
|
namespace :annotate do
task :is_dev do
raise "You can only use this in dev!" unless Rails.env == 'development'
end
desc "annotate your models!"
task :models => :is_dev do
puts "Annotating models"
exec "annotate --exclude tests,fixtures,factories -p before"
end
end
|
require 'open-uri'
require "net/http"
require 'rss'
class Feed < ApplicationRecord
validates_uniqueness_of :url
has_many :articles, dependent: :destroy
before_validation :sanitize_strings
before_save :set_articles
private
def sanitize_strings
attributes.each { |_, value| value.try(:strip!) }
end
def set_articles
if articles.empty?
articles << parse_articles
end
end
def parse_articles
data = open(url)
feed = RSS::Parser.parse(data, false)
self[:name] = feed.channel.title
self[:link] = feed.channel.link
feed.channel.items.collect do | item |
parse_description = Nokogiri::HTML(item.description).css("body").text
item_date = item.date
item_date = DateTime.now if item_date.nil?
new_article = Article.create(title: item.title, description: parse_description , link: item.link, date: item_date.strftime("%B %d, %Y") )
new_article
end
end
end
|
require_dependency 'user_query'
class UsersController < ApplicationController
def index
if params[:followed_by] || params[:followers_of]
if params[:followed_by]
users = User.find(params[:followed_by]).following
elsif params[:followers_of]
users = User.find(params[:followers_of]).followers
end
users = users.page(params[:page]).per(20)
UserQuery.load_is_followed(users, current_user)
render json: users, meta: { cursor: 1 + (params[:page] || 1).to_i }
elsif params[:to_follow]
render json: User.where(to_follow: true), each_serializer: UserSerializer
else
### OLD CODE PATH BELOW. Used only by the recommendations page.
authenticate_user!
status = {
recommendations_up_to_date: current_user.recommendations_up_to_date
}
respond_to do |format|
format.html { redirect_to '/' }
format.json { render json: status }
end
end
end
def show
user = User.find(params[:id])
# Redirect to canonical path
if request.path != user_path(user)
return redirect_to user_path(user), status: :moved_permanently
end
if user_signed_in? && current_user == user
# Clear notifications if the current user is viewing his/her feed.
# TODO: This needs to be moved elsewhere.
Notification.where(user: user, notification_type: 'profile_comment',
seen: false).update_all seen: true
end
respond_with_ember user
end
ember_action(:ember) { User.find(params[:user_id]) }
def follow
authenticate_user!
user = User.find(params[:user_id])
if user != current_user
if user.followers.include? current_user
user.followers.destroy current_user
action_type = 'unfollowed'
else
if current_user.following_count < 10_000
user.followers.push current_user
action_type = 'followed'
else
flash[:message] = "Wow! You're following 10,000 people?! You should \
unfollow a few people that no longer interest you \
before following any others."
action_type = nil
end
end
if action_type
Substory.from_action(
user_id: current_user.id,
action_type: action_type,
followed_id: user.id
)
end
end
respond_to do |format|
format.html { redirect_to :back }
format.json { render json: true }
end
end
def update_avatar
authenticate_user!
user = User.find(params[:user_id])
if user == current_user
user.avatar = params[:avatar] || params[:user][:avatar]
user.save!
respond_to do |format|
format.html { redirect_to :back }
format.json { render json: user, serializer: CurrentUserSerializer }
end
else
error! 403
end
end
def disconnect_facebook
authenticate_user!
current_user.update_attributes(facebook_id: nil)
redirect_to :back
end
def redirect_short_url
@user = User.find_by_name params[:username]
fail ActionController::RoutingError, 'Not Found' if @user.nil?
redirect_to @user
end
def comment
authenticate_user!
# Create the story.
@user = User.find(params[:user_id])
Action.broadcast(
action_type: 'created_profile_comment',
user: @user,
poster: current_user,
comment: params[:comment]
)
respond_to do |format|
format.html { redirect_to :back }
format.json { render json: true }
end
end
def update
authenticate_user!
user = User.find(params[:id])
changes = params[:current_user] || params[:user]
return error!(401, 'Wrong user') unless current_user == user
# Finagling things into place
changes[:cover_image] =
changes[:cover_image_url] if changes[:cover_image_url] =~ /^data:/
changes[:password] =
changes[:new_password] if changes[:new_password].present?
changes[:name] = changes[:new_username] if changes[:new_username].present?
changes[:star_rating] = (changes[:rating_type] == 'advanced')
%i(new_password new_username rating_type cover_image_url).each do |key|
changes.delete(key)
end
changes = changes.permit(:about, :location, :website, :name, :waifu_char_id,
:sfw_filter, :waifu, :bio, :email, :cover_image,
:waifu_or_husbando, :title_language_preference,
:password, :star_rating)
# Convert to hash so that we ignore disallowed attributes
user.assign_attributes(changes.to_h)
if user.save
render json: user
else
return error!(user.errors, 400)
end
end
def to_follow
fixed_user_list = %w(
Gigguk Holden JeanP
Arkada HappiLeeErin DoctorDazza
Yokurama dexbonus DEMOLITION_D
)
@users = User.where(name: fixed_user_list)
render json: @users, each_serializer: UserSerializer
end
end
|
require "rails_helper"
RSpec.feature "AdminCanViewAnInvididualOrder", type: :feature do
let!(:item) do
Item.create(title: "Parka",
description: "Stay warm in the tundra",
price: 3000,
image: "https://s-media-cache-ak0.pinimg.com/236x/90/eb/32/90eb32bc73e010067b15e08cac3ff016.jpg")
end
let!(:admin) { User.create(username: "admin", password: "password", role: 1) }
let!(:user) { User.create(username: "Mitch", password: "supersecret", role: 0) }
let!(:address) { Address.create(street_address: "1510 Blake Street", city: "Denver", state: "CO", zip: "80218", user_id: user.id) }
let!(:order) { Order.create(user_id: user.id, status: 0) }
let!(:order_item) { OrderItem.create(quantity: 2, item_id: item.id, order_id: order.id) }
context "logged in as an admin and viewing a single order" do
before do
ApplicationController.any_instance.stubs(:current_user).returns(admin)
end
it "views all orders for all users" do
visit admin_order_path(order)
expect(page).to have_content("Order #{order.id}")
expect(page).to have_content("Created on #{order.created_at.strftime("%b %d, %Y")} at #{order.created_at.strftime("%I:%M:%S %p")}")
expect(page).to have_content("Customer: Mitch")
expect(page).to have_content("Shipping Address: 1510 Blake Street, Denver CO 80218")
within("#order-info") do
expect(page).to have_content("Parka")
expect(page).to have_content("Quantity: 2")
expect(page).to have_content("Price: $3,000.00")
expect(page).to have_content("Subtotal: $6,000.00")
end
expect(page).to have_content("Total: $6,000.00")
end
end
end
|
class ReferencesController < ApplicationController
before_action :require_admin
def new
@reference = Reference.new
end
def create
Reference.create(reference_params)
redirect_to resume_path
end
def edit
@reference = Reference.find(params[:id])
end
def update
@reference = Reference.find(params[:id])
@reference.update(reference_params)
redirect_to resume_path
end
def destroy
Reference.find(params[:id]).destroy
redirect_to resume_path
end
protected
def reference_params
params.require(:reference).permit(:name, :telephone, :email, :relationship, :endorsement)
end
end
|
require 'prawn_charts/layers/layer'
module PrawnCharts
module Layers
# Bar graph.
class Bar < Layer
def draw(pdf, coords, options = {})
#puts "bar draw options #{options.awesome_inspect}"
options.merge!(@options)
marker = options[:marker] || nil
pdf.reset_text_marks
theme.reset_color
coords.each_with_index do |coord,idx|
next if coord.nil?
color = preferred_color || theme.next_color
x, y, bar_width = (coord.first), coord.last, 1#(width - coord.last)
valw = max_value + min_value * -1 #value_width
maxw = max_value * width / valw #positive area width
minw = min_value * width / valw #negative area width
if points[idx] > 0
bar_width = points[idx]*maxw/max_value
else
bar_width = points[idx]*minw/min_value
end
#pdf.text_mark "bar rect [#{x},#{y}], #{@bar_height}, #{bar_width}"
pdf.centroid_mark([x+bar_width/2.0,height-y-@bar_height/2.0],:radius => 3)
pdf.crop_marks([x,height-y],bar_width,@bar_height)
current_color = color.is_a?(Array) ? color[idx % color.size] : color
pdf.fill_color current_color
#alpha = 1.0
#pdf.transparent(alpha) do
pdf.fill_rectangle([0.0,height-y], bar_width, @bar_height)
#end
if options[:border]
theme.reset_outline
pdf.stroke_color theme.next_outline
pdf.stroke_rectangle([0.0,height-y],bar_width, @bar_height)
end
end
if marker
marker_size = options[:marker_size]
marker_size = (options[:relative]) ? relative(marker_size) : marker_size
theme.reset_color
coords.each do |coord|
x, y = (coord.first), height-coord.last
color = preferred_color || theme.next_color
draw_marker(pdf,marker,width-x,y-@bar_height/2.0,marker_size,color)
end
end
end
def legend_data
if relevant_data? && @color
retval = []
if titles && !titles.empty?
titles.each_with_index do |stitle, index|
retval << {:title => stitle,
:color => @colors[index],
:priority => :normal}
end
end
retval
else
nil
end
end
protected
# Due to the size of the bar graph, X-axis coords must
# be squeezed so that the bars do not hang off the ends
# of the graph.
#
# Unfortunately this just mean that bar-graphs and most other graphs
# end up on different points. Maybe adding a padding to the coordinates
# should be a graph-wide thing?
#
# Update : x-axis coords for lines and area charts should now line
# up with the center of bar charts.
def generate_coordinates(options = {})
dy = @options[:explode] ? relative(@options[:explode]) : 0
@bar_height = (height / points.size)-dy
options[:point_distance] = (height - @bar_height ) / (points.size - 1).to_f
coords = (0...points.size).map do |idx|
next if points[idx].nil?
y_coord = (options[:point_distance] * idx) + (height / points.size * 0.5) - (@bar_height * 0.5) - dy/2.0
relative_percent = ((points[idx] == min_value) ? 0 : ((points[idx] - min_value) / (max_value - min_value).to_f))
x_coord = (width - (width * relative_percent))
[x_coord, y_coord]
end
coords
end
end # Bar
end # Layers
end # PrawnCharts |
module Spaces
class UpdatesSpaces
def initialize(params: {})
@params = params
@repo = Repository.for(:space)
end
def update(space)
updated_space = Space.new space.value.merge(params)
@repo.save updated_space
end
private
attr_reader :params
end
end
|
require 'rails_helper'
RSpec.describe "can create links", :js => :true do
scenario "Create a new link" do
user = User.create(email: "test@gmail.com", password: "123", password_confirmation: "123")
allow_any_instance_of(ApplicationController).to receive(:current_user).and_return(user)
visit '/'
fill_in "link-url", with: "http://www.google.com"
fill_in "link-title", with: "Google"
click_button "Add Link"
expect(page).to have_content("http://www.google.com")
expect(page).to have_content("Google")
end
scenario "Edit link" do
user = User.create(email: "test@gmail.com", password: "123", password_confirmation: "123")
allow_any_instance_of(ApplicationController).to receive(:current_user).and_return(user)
Link.create(title: "This", url: "http://www.test.com", user_id: user.id)
visit '/'
click_on "Edit"
expect(current_path).to eq(edit_link_path(Link.last))
fill_in "link[title]", with: "Bam"
click_on "Update Link"
expect(page).to have_content("Link was successfully updated")
end
scenario "Edit link with bad url" do
user = User.create(email: "test@gmail.com", password: "123", password_confirmation: "123")
allow_any_instance_of(ApplicationController).to receive(:current_user).and_return(user)
Link.create(title: "This", url: "http://www.test.com", user_id: user.id)
visit '/'
click_on "Edit"
expect(current_path).to eq(edit_link_path(Link.last))
fill_in "link[url]", with: "Bam"
click_on "Update Link"
expect(page).to have_content("Link failed to update. URL must be valid and lead with 'http://' or 'https://'")
end
end
|
require 'spec_helper'
describe ::Treasury::HashSerializer do
let(:serializer) { serializer_class.new }
let(:serializer_class) do
Class.new { extend ::Treasury::HashSerializer }
end
describe '#serialize' do
let(:serialize) { serializer_class.serialize(value) }
context 'when value is nil' do
let(:value) { nil }
it { expect(serialize).to eq nil }
end
context 'when value is empty' do
let(:value) { {} }
it { expect(serialize).to eq nil }
end
context 'when value ok' do
let(:value) { {123 => 321, 234 => 432} }
it { expect(serialize).to eq '123:321,234:432' }
end
end
describe '#deserialize' do
let(:deserialize) { serializer_class.deserialize(value) }
context 'when value is nil' do
let(:value) { nil }
it { expect(deserialize).to eq({}) }
end
context 'when value is empty' do
let(:value) { '' }
it { expect(deserialize).to eq({}) }
end
context 'when value ok' do
let(:value) { '123:321,234:432,100:-3' }
it { expect(deserialize).to eq('123' => 321, '234' => 432, '100' => -3) }
end
end
end
|
class ItemPurchase
include ActiveModel::Model
attr_accessor :postal_code,
:prefecture_id,
:city,
:block,
:building,
:phone_number,
:user_id,
:item_id,
:token
with_options presence: true do
validates :token
validates :postal_code, format: { with: /\A\d{3}-\d{4}\z/, message: 'Input correctly' }
validates :prefecture_id, numericality: { other_than: 0, message: 'Select' }
validates :city
validates :block
validates :phone_number, format: { with: /\A\d{1,11}\z/, message: 'Input only number' }
validates :user_id
validates :item_id
end
def save
useritem = UserItem.create(user_id: user_id,
item_id: item_id)
Address.create(postal_code: postal_code,
prefecture_id: prefecture_id,
city: city,
block: block,
building: building,
phone_number: phone_number,
user_item_id: useritem.id)
end
end
|
class Getmail < Formula
homepage "http://pyropus.ca/software/getmail/"
url "http://pyropus.ca/software/getmail/old-versions/getmail-4.47.0.tar.gz"
mirror "https://fossies.org/linux/misc/getmail-4.47.0.tar.gz"
sha256 "4b5accd3d0d79e1a84c0aed850ac8717b7f6e9ad72cfab7ba22abf58638e4540"
# See: https://github.com/Homebrew/homebrew/pull/28739
patch do
url "https://gist.githubusercontent.com/sigma/11295734/raw/5a7f39d600fc20d7605d3c9e438257285700b32b/ssl_timeout.patch"
sha1 "d7242a07c0d4de1890bb8ebd51b55e01e859b302"
end
def install
libexec.install %w[getmail getmail_fetch getmail_maildir getmail_mbox]
bin.install_symlink Dir["#{libexec}/*"]
libexec.install "getmailcore"
man1.install Dir["docs/*.1"]
end
test do
system bin/"getmail", "--help"
end
end
|
# frozen_string_literal: true
RSpec.describe SC::Billing::Stripe::Webhooks::Charges::PendingOperation, :stripe do
let(:webhook_operation) { described_class.new }
describe '#call' do
subject(:call) do
webhook_operation.call(event)
end
let(:event) { StripeMock.mock_webhook_event('charge.pending') }
let(:event_data) { event.data.object }
context 'when charge exists' do
let!(:charge) { create(:stripe_charge, stripe_id: 'ch_00000000000000') }
it 'updates charge' do
expect { call }.to(
change { charge.reload.updated_at }
)
end
end
context 'when charge does not exist' do
before do
create(:user, stripe_customer_id: 'cus_00000000000000')
end
it 'creates charge' do
expect { call }.to change(::SC::Billing::Stripe::Charge, :count).by(1)
end
end
end
end
|
module KoiVMRuby
class VM
@@instruction[PUSH_STRING] = Proc.new() do |vm|
operand = vm.opcodes[vm.instruction_pointer + 1]
raise OperandError, "Expecting string value but got #{operand.inspect}" unless(operand.is_a?(String))
vm.data_stack.push([STRING_, operand])
vm.instruction_pointer = vm.instruction_pointer + 2
end
end
end |
class Msponsor < ActiveRecord::Base
belongs_to :mobject
#belongs_to :user
belongs_to :company
has_many :tickets
end
|
require 'spec_helper'
describe "vendors/new" do
before(:each) do
assign(:vendor, stub_model(Vendor,
:vendor_code => "MyString",
:name => "MyString",
:address1 => "MyString",
:address2 => "MyString",
:city => "MyString",
:state => "MyString",
:zip_code => "MyString",
:phone => "MyString",
:contact => "MyString",
:email => "MyString"
).as_new_record)
end
it "renders new vendor form" do
render
# Run the generator again with the --webrat flag if you want to use webrat matchers
assert_select "form", :action => vendors_path, :method => "post" do
assert_select "input#vendor_vendor_code", :name => "vendor[vendor_code]"
assert_select "input#vendor_name", :name => "vendor[name]"
assert_select "input#vendor_address1", :name => "vendor[address1]"
assert_select "input#vendor_address2", :name => "vendor[address2]"
assert_select "input#vendor_city", :name => "vendor[city]"
assert_select "input#vendor_state", :name => "vendor[state]"
assert_select "input#vendor_zip_code", :name => "vendor[zip_code]"
assert_select "input#vendor_phone", :name => "vendor[phone]"
assert_select "input#vendor_contact", :name => "vendor[contact]"
assert_select "input#vendor_email", :name => "vendor[email]"
end
end
end
|
class EntityContext < ActiveRecord::Base
attr_accessible :name, :properties, :application, :title
store :properties
validates :name, :presence => true, :uniqueness => true
validates :title, :presence => true
belongs_to :application
validates_associated :application
has_many :entities, :foreign_key => :context_id
end
|
#
# Assumes existence of session_url which can be POSTed to
# with credentials.
#
module AuthenticationHelper
def sign_in_as(user)
credentials = {
session: {
username: user.email,
password: "secret",
},
}
post session_url, params: credentials
expect(response).to have_http_status(:created)
expect(session[:user_id]).to eql user.id
end
end
RSpec.configure do |config|
config.include AuthenticationHelper, type: :request
config.include AuthenticationHelper, type: :feature
end
|
require 'spec_helper'
describe "StaticPages" do
describe "Home page" do
it "should have the content 'UniverGenex'" do
visit '/static_pages/home'
page.should have_selector('h1', :text=> 'UniverGenex Application')
end
end
it "should have the title 'Home'" do
visit '/static_pages/home'
page.should have_selector('title',
:text => "UniverGenex Application | Home")
end
end
|
require 'active_support/core_ext/hash/keys'
require 'active_support/core_ext/hash/indifferent_access'
module Telegram
module Bot
module ConfigMethods
# Overwrite config.
attr_writer :bots_config
# Keep this setting here, so we can avoid loading Bot::UpdatesPoller
# when polling is disabled.
attr_writer :bot_poller_mode
# It just tells routes helpers whether to add routed bots to
# Bot::UpdatesPoller, so their config will be available by bot key in
# Bot::UpdatesPoller.start.
#
# It's enabled by default in Rails dev environment and `rake telegram:bot:poller`
# task. Use `BOT_POLLER_MODE=true` envvar to set it manually.
def bot_poller_mode?
return @bot_poller_mode if defined?(@bot_poller_mode)
@bot_poller_mode = ENV.fetch('BOT_POLLER_MODE') do
Rails.env.development? if defined?(Rails.env)
end
end
# Hash of bots made with bots_config.
def bots
@bots ||= bots_config.each_with_object({}) do |(id, config), h|
h[id] = Client.wrap(config, id: id)
end
end
# Default bot.
def bot
@bot ||= bots.fetch(:default) do
raise 'Default bot is not configured.' \
' Add :default to bots_config' \
' or use telegram.bot/telegram.bots.default section in secrets.yml.'
end
end
# Returns config for .bots method. By default uses `telegram['bots']` section
# from `secrets.yml` merging `telegram['bot']` at `:default` key.
#
# Can be overwritten with .bots_config=
def bots_config
@bots_config ||=
if defined?(Rails.application)
app = Rails.application
store = app.credentials[:telegram] if app.respond_to?(:credentials)
store ||= app.secrets[:telegram] if app.respond_to?(:secrets)
store ||= {}
store = store.with_indifferent_access
store.fetch(:bots, {}).symbolize_keys.tap do |config|
default = store[:bot]
config[:default] = default if default
end
else
{}
end
end
# Resets all cached bots and their configs.
def reset_bots
@bots = nil
@bot = nil
@bots_config = nil
end
end
end
end
|
require 'spec_helper'
require 'securerandom'
require 'crypto_gost3411'
describe CryptoGost3410 do
context 'crypto_gost3410' do
NAMES = %w[
Gost256tc26test
Gost256tc26a
Gost256tc26b
Gost256tc26c
Gost256tc26d
Gost512tc26test
Gost512tc26a
Gost512tc26b
Gost512tc26c
].freeze
NAMES.each do |name|
context name do
let(:group) { Object.const_get("CryptoGost3410::Group::#{name}") }
let(:private_key) { SecureRandom.random_number(1..group.order-1) }
let(:public_key) { group.generate_public_key private_key }
let(:message) { Faker::Lorem.sentence(3) }
let(:coord_size) { group.opts[:coord_size] }
let(:digest) { CryptoGost3411::Gost3411.new(coord_size).update(message).final }
let(:digest_num) { CryptoGost3410::Converter.bytesToBignum(digest.reverse) }
let(:generator) { CryptoGost3410::Generator.new(group) }
let(:rand_val) { SecureRandom.random_number(1..group.order-1) }
let(:signature) { generator.sign(digest_num, private_key, rand_val) }
let(:verifier) { CryptoGost3410::Verifier.new(group) }
let(:another_message) { Faker::Lorem.sentence(2) }
let(:another_digest) { CryptoGost3411::Gost3411.new(coord_size).update(another_message).final}
let(:another_digest_num) { CryptoGost3410::Converter.bytesToBignum(another_digest.reverse) }
let(:receiver_private_key) { SecureRandom.random_number(1..group.order-1) }
let(:receiver_public_key) { group.generate_public_key receiver_private_key }
let(:ukm) { SecureRandom.random_number(2**(coord_size*2)..2**(coord_size*8)-1) }
let(:sender_vko) { generator.vko(ukm, private_key, receiver_public_key) }
let(:receiver_vko) { generator.vko(ukm, receiver_private_key, public_key) }
it 'find group by name' do
expect(CryptoGost3410::Group.findByName(group.opts[:name]) == group).to be_truthy
end
it 'find group by id' do
expect(CryptoGost3410::Group.findById(group.opts[:id]) == group).to be_truthy
end
it 'find group by oid' do
expect(CryptoGost3410::Group.findByOid(group.opts[:oid]) == group).to be_truthy
end
it 'find group by der oid' do
expect(CryptoGost3410::Group.findByDerOid(group.opts[:der_oid]) == group).to be_truthy
end
it 'has valid signature' do
expect(verifier.verify(digest_num, public_key, signature)).to be_truthy
end
it 'has invalid signature for changed message' do
expect(verifier.verify(another_digest_num, public_key, signature)).to be_falsy
end
it 'sender VKO equals to receiver VKO' do
expect((sender_vko.x == receiver_vko.x) && (sender_vko.y == receiver_vko.y)).to be_truthy
end
end
end
end
end
|
#!/usr/bin/env ruby
# ^^ sets the command line environment
require 'faraday'
require 'sinatra'
require 'json'
set :port, ENV["PORT"]
conn = Faraday.new(url: "https://slack.com")
post '/message_posted' do
# ideally you would send a response back to slack and then do all the prep
# for the follow-up action
begin
request.body.rewind
request_data = JSON.parse(request.body.read)
puts request_data["text"]
return unless request_data["text"] =~ /hello/
if channel = request_data["channel"]
conn.post "/api/chat.postMessage", { token: key, channel: channel["id"], text: "hi back! tofuuu" }
end
rescue JSON::ParserError
status 400
{ error: "invalid request format" }.to_json
end
end
# # to access the API, you need a Slack URL endpoint:
# # url = "https://slack.com/api/channels.list"
# key = ENV["SLACK_API_KEY"]
#
# conn = Faraday.new(url: "https://slack.com")
# response = conn.post "/api/channels.list", { token: key }
#
# unless response.success?
# puts "API did not return a success :("
# puts response.body
# exit
# end
#
# parsed_response = JSON.parse(response.body)
# channels = parsed_response["channels"]
# if channels
# general_channel = channels.find { |c| c["name"] == "general" }
# response = conn.post "/api/chat.postMessage", { token: key, channel: general_channel["id"], text: "tofu!" }
# if response.success?
# puts "yay! check slack"
# else
# puts "oh no :("
# puts response.body
# end
# end
|
# Definition for a binary tree node.
class TreeNode
attr_accessor :val, :left, :right
def initialize(val = 0, left = nil, right = nil)
@val = val
@left = left
@right = right
end
end
# @param {TreeNode} root
# @param {Integer} val
# @return {TreeNode}
def search_bst(root, val)
return nil if root.nil?
return root if root.val == val
return search_bst(root.left,val) if root.val > val
return search_bst(root.right,val) if root.val < val
end |
require 'email_validator'
require 'mail'
class User < ActiveRecord::Base
has_merit
acts_as_voter
searchkick autocomplete: ['name']
def search_data
{
name: name,
}
end
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable, :confirmable,
:recoverable, :rememberable, :trackable, :validatable #, :confirmable
belongs_to :group
before_create :assign_to_group
has_many :activities, dependent: :destroy
has_many :bookings, dependent: :destroy
has_many :favorite_sports, dependent: :destroy
has_many :location_reviews, dependent: :destroy
has_many :newsfeeds, dependent: :destroy
validates :email, :presence => true, :email => true
has_attached_file :picture,
styles: { medium: "300x300#", thumb: "100x100>" }
validates_attachment_content_type :picture,
content_type: /\Aimage\/.*\z/
private
def assign_to_group
if self.email.include?("stationf")
self.group = Group.find_by(email_domain_name: "stationf.co")
elsif self.email.include?("thalasseo")
self.group = Group.find_by(email_domain_name: "voyageprive.com")
else
self.group = Group.find_by(email_domain_name: Mail::Address.new(self.email).domain)
end
end
end
|
# ΠΠ°Π·ΠΎΠ²ΡΠΉ ΠΊΠΎΠ½ΡΡΠΎΠ»Π»Π΅Ρ ΠΊΠΎΠ½ΡΠ΅Π½ΡΠ½ΠΎΠΉ ΡΠ°ΡΡΠΈ ΡΠ°ΠΉΡΠ°
# Π² Π½Π΅ΠΌ ΠΏΡΠΎΠΈΡΡ
ΠΎΠ΄ΠΈΡ ΠΊΡΡΠ° Π²ΡΡΠΊΠΎΠΉ Π²ΡΡΡΠΈΠ½Ρ:
# - ΠΎΡΠ»Π°Π²Π»ΠΈΠ²Π°Π½ΠΈΠ΅ ΠΎΡΠΈΠ±ΠΎΠΊ
# - ΠΎΠΏΡΠ΅Π΄Π΅Π»Π΅Π½ΠΈΠ΅ ΡΠ΅ΠΊΡΡΠ΅ΠΉ ΡΡΡΠ°Π½ΠΈΡΡ
# - ΠΈΠ½ΠΈΡΠΈΠ°Π»ΠΈΠ·Π°ΡΠΈΡ ΠΊΠΎΡΠ·ΠΈΠ½Ρ (Π΅ΡΠ»ΠΈ ΡΠ°ΠΊΠΎΠ²Π°Ρ ΠΈΠΌΠ΅Π΅ΡΡΡ)
class Content::BaseController < ApplicationController
layout 'content'
helper Content::ContentHelper
helper Content::CartHelper
include TranslateHelper
before_action :get_locale
before_action :get_path
before_action :set_token
before_action :set_cart
class UnknownLocaleException < StandardError; end
class PageNotFound < StandardError; end
rescue_from UnknownLocaleException, :with => :show404
rescue_from PageNotFound, :with => :show404
def show404()
render 'errors/error_404', layout: 'content'
end
def index
render 'content/index', layout: "map"
end
def show
end
def item
end
def list
end
def meta
get_meta
end
protected
def set_token
@token = cookies['_token'].present? ? cookies['_token'] : Order::Cart.token
end
def set_cart
@cart = Order::Cart.find_by_token_and_order_status_id @token, nil
unless @cart
@token = Order::Cart.token
@cart = Order::Cart.create({token: @token, language: @language})
end
@cart.language = @language
cookies['_token'] = @token
end
def get_item
@current_page
end
def page_title_suffix
''
end
def page_title_prefix
''
end
def get_meta
item = get_item
if item.nil?
item = @current_page
end
if item
title = []
# ΠΊΠΎΠ½ΡΡΠΎΠ»Π»Π΅Ρ Π½Π°ΡΠ»Π΅Π΄ΡΠ΅ΡΡΡ,
# Π° Π² Π΄ΠΎΡΠ΅ΡΠ½ΠΈΡ
ΠΌΠΎΠΆΠ½ΠΎ ΠΏΠ΅ΡΠ΅ΠΎΠΏΡΠ΅Π΄Π΅Π»ΠΈΡΡ ΠΌΠ΅ΡΠΎΠ΄Ρ
# page_title_prefix ΠΈ page_title_suffix
title << page_title_prefix.to_s if page_title_prefix
title << item.title.to_s if item.title
title << page_title_suffix.to_s if page_title_suffix
{
title: title.join(" "),
heading: item.heading,
keywords: item.keywords,
description: item.description
}
else
{}
end
end
def get_path
@current_page = nil
Rails.application.routes.router.recognize(request) do |route, matches, param|
#@asd = ContentRouter.routes
#abort @asd.inspect
page = ContentRouter.routes.each do |r|
if r[:as] == route.name or (r[:applies_to] and r[:applies_to].include?(route.name))
@current_page = r[:page]
@current_menu_item = r[:active]
break
end
end
end
end
def get_locale
@language = Language.find_by_slug params[:locale]
unless @language
@language = Language.find_by_is_default(true)
end
I18n.locale = @language.slug || I18n.default_locale
end
def default_url_options
{ locale: I18n.locale }
end
def render_error(status, exception)
respond_to do |format|
format.html { render template: "errors/error_#{status}", layout: 'errors', status: status }
format.all { render nothing: true, status: status }
end
end
end |
# How does take work? Is it destructive?
arr = [1, 2, 3, 4, 5]
arr.take(2)
# Ruby docs: take(n) --> new_array
# Returns a new array containing the first n element of self, where n is a non-negative integer; does not modify self.
# => [1, 2]
arr #=> [1, 2, 3, 4, 5] it is not destructive
|
class ProjectSchemaQuestions < ActiveRecord::Migration
def self.up
create_table :project_schema_questions do |t|
t.integer :position
t.integer :project_schema_id
t.integer :question_id
t.timestamps
end
end
def self.down
drop_table :project_schema_questions
end
end
|
module Types
class BaseCurrency < Types::BaseObject
description "The base currency used to convert values to understandable fiat money"
field :id, ID, null: false
field :code, String, null: false
field :exchange_rate, Float, null: false
field :symbol, String, null: false
field :full_name, String, null: false
field :created_at, GraphQL::Types::ISO8601DateTime, null: false
field :updated_at, GraphQL::Types::ISO8601DateTime, null: false
field :user_settings, [Types::UserSetting], null: true
end
end
|
describe ManageIQ::Providers::Amazon::CloudManager::CloudDatabase do
let(:ems) do
FactoryBot.create(:ems_amazon)
end
let(:cloud_database) do
FactoryBot.create(:cloud_database_amazon, :ext_management_system => ems, :name => "test-db")
end
describe 'cloud database actions' do
let(:connection) do
double("Aws::RDS::Resource")
end
let(:rds_client) do
double("Aws::RDS::Client")
end
before do
allow(ems).to receive(:with_provider_connection).and_yield(connection)
allow(connection).to receive(:client).and_return(rds_client)
end
context '#create_cloud_database' do
it 'creates the cloud database' do
expect(rds_client).to receive(:create_db_instance).with(:db_instance_identifier => "test-db",
:db_instance_class => "db.t2.micro",
:allocated_storage => 5,
:engine => "mysql",
:master_username => "test123",
:master_user_password => "test456")
cloud_database.class.raw_create_cloud_database(ems, {:name => "test-db",
:flavor => "db.t2.micro",
:storage => 5,
:database => "mysql",
:username => "test123",
:password => "test456"})
end
end
context '#delete_cloud_database' do
it 'deletes the cloud database' do
expect(rds_client).to receive(:delete_db_instance).with(:db_instance_identifier => cloud_database.name, :skip_final_snapshot => true)
cloud_database.delete_cloud_database
end
end
end
end
|
class RemoveSongsBroadcastsCount < ActiveRecord::Migration
def change
remove_column :songs, :broadcasts_count
end
end
|
require_relative '../framework/renderer.rb'
require 'fileutils'
describe Renderer do
before :all do
FileUtils.mkdir_p("render_tests/nested")
index_content = "<h1>Hello</h1><%= 1 + 2 %>"
nested_content = "<p>nested <%= 5 + 6 %></p>"
File.write("render_tests/index.erb", index_content)
File.write("render_tests/nested/_nested.erb", nested_content)
end
describe "[]" do
it "initializes a renderer with a queue" do
renderer = Renderer['render_tests']
expect(renderer.queue.empty?).to be false
end
end
describe "render" do
it "renders template files as siblings" do
Renderer['render_tests'].render
expect(File.exist? "render_tests/index.html").to be true
end
it "does not render _template files" do
Renderer['render_tests'].render
expect(File.exist? "render_tests/nested/_index.html").to be false
end
it "correctly renders self-contained content" do
Renderer['render_tests'].render
expected = "<h1>Hello</h1>3"
expect(File.read "render_tests/index.html").to eq(expected)
end
it "correctly renders self-contained content to new dir" do
Renderer['render_tests'].render(out: "./render_dist")
expect(File.exist? "./render_dist/index.html").to be true
expect(File.exist? "./render_tests/index.html").to be false
FileUtils.rm_rf("./render_dist")
end
it "correctly preserves folder structure in new dir" do
File.write("render_tests/nested/another.erb", "<p>Hi</p>")
Renderer['render_tests'].render(out: "./render_dist")
expect(File.exist? "./render_dist/index.html").to be true
expect(File.exist? "./render_tests/index.html").to be false
expect(File.exist? "./render_dist/nested/another.html").to be true
expect(File.exist? "./render_tests/nested/another.html").to be false
FileUtils.rm_rf("./render_dist")
end
end
describe "render_internal" do
it "correctly renders references" do
index_content = "<%= render_internal \"nested/_nested.erb\" %>"
File.write('render_tests/index.erb', index_content)
result = Renderer['render_tests'].render_internal('index.erb')
expect(result).to eq("<p>nested 11</p>")
end
it "correctly passes data to references" do
index_content = "<%= render_internal \"nested/_nested.erb\", {a: 'data'} %>"
File.write('render_tests/index.erb', index_content)
nested_content = "<p>nested <%= a %></p>"
File.write('render_tests/nested/_nested.erb', nested_content)
result = Renderer['render_tests'].render_internal('index.erb')
expect(result).to eq("<p>nested data</p>")
end
end
after :each do
FileUtils.rm(Dir['render_tests/**/*.html'])
end
after :all do
FileUtils.rm_rf("render_tests")
end
end
|
FactoryGirl.define do
factory_by_attribute = {
actions: :dummy_module_action,
module_references: :dummy_module_reference,
}
factory :dummy_module_instance,
:class => Dummy::Module::Instance,
:traits => [
:metasploit_model_base,
:metasploit_model_module_instance
] do
#
# Associations
#
association :module_class, :factory => :dummy_module_class
# attribute must be called after association is created so that support_stance? has access to module_class
# needs to be declared explicitly after association as calling trait here (instead as an argument to factory
# :traits) did not work.
stance {
if stanced?
generate :metasploit_model_module_stance
else
nil
end
}
# needs to be an after(:build) and not an after(:create) to ensure counted associations are populated before being
# validated.
after(:build) do |dummy_module_instance, evaluator|
dummy_module_instance.module_authors = evaluator.module_authors_length.times.collect {
FactoryGirl.build(:dummy_module_author, module_instance: dummy_module_instance)
}
module_class = dummy_module_instance.module_class
# only attempt to build supported associations if the module_class is valid because supports depends on a valid
# module_type and validating the module_class will derive module_type.
if module_class && module_class.valid?
factory_by_attribute.each do |attribute, factory|
if dummy_module_instance.allows?(attribute)
length = evaluator.send("#{attribute}_length")
collection = length.times.collect {
FactoryGirl.build(factory, module_instance: dummy_module_instance)
}
dummy_module_instance.send("#{attribute}=", collection)
end
end
# make sure targets are generated first so that module_architectures and module_platforms can be include
# the targets' architectures and platforms.
if dummy_module_instance.allows?(:targets)
# factory adds built module_targets to module_instance.
FactoryGirl.build_list(
:dummy_module_target,
evaluator.targets_length,
module_instance: dummy_module_instance
)
# module_architectures and module_platforms will be derived from targets
else
# if there are no targets, then architectures and platforms need to be explicitly defined on module instance
# since they can't be derived from anything
[:architecture, :platform].each do |suffix|
attribute = "module_#{suffix.to_s.pluralize}".to_sym
if dummy_module_instance.allows?(attribute)
factory = "dummy_module_#{suffix}"
length = evaluator.send("#{attribute}_length")
collection = FactoryGirl.build_list(
factory,
length,
module_instance: dummy_module_instance
)
dummy_module_instance.send("#{attribute}=", collection)
end
end
end
end
end
end
end |
require "spec_helper"
describe "Missing Attachment Styles" do
before do
Paperclip::AttachmentRegistry.clear
end
after do
begin
File.unlink(Paperclip.registered_attachments_styles_path)
rescue StandardError
nil
end
end
it "enables to get and set path to registered styles file" do
assert_equal ROOT.join("tmp/public/system/paperclip_attachments.yml").to_s, Paperclip.registered_attachments_styles_path
Paperclip.registered_attachments_styles_path = "/tmp/config/paperclip_attachments.yml"
assert_equal "/tmp/config/paperclip_attachments.yml", Paperclip.registered_attachments_styles_path
Paperclip.registered_attachments_styles_path = nil
assert_equal ROOT.join("tmp/public/system/paperclip_attachments.yml").to_s, Paperclip.registered_attachments_styles_path
end
it "is able to get current attachment styles" do
assert_equal Hash.new, Paperclip.send(:current_attachments_styles)
rebuild_model styles: { croppable: "600x600>", big: "1000x1000>" }
expected_hash = { Dummy: { avatar: [:big, :croppable] } }
assert_equal expected_hash, Paperclip.send(:current_attachments_styles)
end
it "is able to save current attachment styles for further comparison" do
rebuild_model styles: { croppable: "600x600>", big: "1000x1000>" }
Paperclip.save_current_attachments_styles!
expected_hash = { Dummy: { avatar: [:big, :croppable] } }
assert_equal expected_hash, YAML.load_file(Paperclip.registered_attachments_styles_path)
end
it "is able to read registered attachment styles from file" do
rebuild_model styles: { croppable: "600x600>", big: "1000x1000>" }
Paperclip.save_current_attachments_styles!
expected_hash = { Dummy: { avatar: [:big, :croppable] } }
assert_equal expected_hash, Paperclip.send(:get_registered_attachments_styles)
end
it "is able to calculate differences between registered styles and current styles" do
rebuild_model styles: { croppable: "600x600>", big: "1000x1000>" }
Paperclip.save_current_attachments_styles!
rebuild_model styles: { thumb: "x100", export: "x400>", croppable: "600x600>", big: "1000x1000>" }
expected_hash = { Dummy: { avatar: [:export, :thumb] } }
assert_equal expected_hash, Paperclip.missing_attachments_styles
ActiveRecord::Base.connection.create_table :books, force: true
class ::Book < ActiveRecord::Base
has_attached_file :cover, styles: { small: "x100", large: "1000x1000>" }
has_attached_file :sample, styles: { thumb: "x100" }
end
expected_hash = {
Dummy: { avatar: [:export, :thumb] },
Book: { sample: [:thumb], cover: [:large, :small] }
}
assert_equal expected_hash, Paperclip.missing_attachments_styles
Paperclip.save_current_attachments_styles!
assert_equal Hash.new, Paperclip.missing_attachments_styles
end
it "is able to calculate differences when a new attachment is added to a model" do
rebuild_model styles: { croppable: "600x600>", big: "1000x1000>" }
Paperclip.save_current_attachments_styles!
class ::Dummy
has_attached_file :photo, styles: { small: "x100", large: "1000x1000>" }
end
expected_hash = {
Dummy: { photo: [:large, :small] }
}
assert_equal expected_hash, Paperclip.missing_attachments_styles
Paperclip.save_current_attachments_styles!
assert_equal Hash.new, Paperclip.missing_attachments_styles
end
# It's impossible to build styles hash without loading from database whole bunch of records
it "skips lambda-styles" do
rebuild_model styles: lambda { |attachment| attachment.instance.other == "a" ? { thumb: "50x50#" } : { large: "400x400" } }
assert_equal Hash.new, Paperclip.send(:current_attachments_styles)
end
end
|
$: << File.expand_path(File.dirname(__FILE__) + '/../../../lib')
require 'indication_dispatchers/free_first_aid_video'
include IndicationDispatchers
class FirstAidVideoOrder
attr_accessor :items
def initialize
@items = []
end
def add_line_item(line_item)
@items << { line_item.item_name => {price: line_item.item_price} }
end
end
describe FreeFirstAidVideo do
before do
Item.stub(:new).with("First Aid").
and_return(OpenStruct.new(name: "First Aid", price: 0))
@order = FirstAidVideoOrder.new
@dispatcher = FreeFirstAidVideo.new(@order)
end
it "adds the first aid video item" do
@dispatcher.run
@order.items.should include("First Aid" => {price: 0})
end
end
|
require 'benchmark'
def generate_primes(max_prime)
@prime_hash = Hash.new { |h,k| h[k] = true }
@primes = [ 2 ]
3.step(max_prime, 2) do |next_prime|
if(@prime_hash[next_prime])
@primes << next_prime
if(next_prime < Math.sqrt(max_prime))
next_prime.step(max_prime/next_prime, 2) { |i| @prime_hash[i * next_prime] = false }
end
end
end
end
max = 10**6
Benchmark.bm(40) do |bm|
5.times do
bm.report("Generating all primes less than #{max}") do
generate_primes(max)
end
end
end
|
class AddCommutingCommutesIdToCommutingStopEvents < ActiveRecord::Migration
def change
add_column :commuting_stop_events, :commuting_commute_id, :integer
add_reference :commuting_stop_events, :commuting_commutes, index: true, foreign_key: true
end
end
|
class UsersController < ApplicationController
def create
user = User.create(user_params)
payload = {user_id: user.id}
token = JWT.encode(payload, secret, 'HS256')
render json: {user: user, token: token}
# render json: user
end
def destroy
user = User.find_by(id: params[:user_id])
# byebug
user.destroy
render json: { success: "Woohoooo"}
end
private
def user_params
params.permit(:username, :password)
end
end |
class TransactionsController < ApplicationController
skip_before_action :verify_authenticity_token
def create
@new_transaction = Transaction.create(transaction_params)
if @new_transaction.valid?
render json: @new_transaction.as_json, status: :created
else
render json: @new_transaction.errors.messages, status: :bad_request
end
end
def transaction_params
params.permit(:total_spent_in_cents, :user_id, :country)
end
end |
# frozen_string_literal: true
class DataModel
PUNCTUATORS = /([,.!?β])/.freeze
def self.prepare(text)
tokens = tokenize(text)
tokens.each_with_object(Hash.new([])).with_index do |(token, holder), index|
next if index == tokens.length - 1
holder[token] += [tokens[index + 1]]
end
end
def self.tokenize(text)
text.downcase.split(/\s+/).flat_map do |subtext|
subtext.split(PUNCTUATORS)
end
end
end
|
# encoding: UTF-8
# frozen_string_literal: true
module Geos::GoogleMaps
module Api3
end
module Api3Constants
UNESCAPED_MARKER_OPTIONS = %w{
icon
map
position
shadow
shape
}.freeze
UNESCAPED_POLY_OPTIONS = %w{
clickable
fillOpacity
geodesic
map
path
paths
strokeOpacity
strokeWeight
zIndex
}.freeze
end
module Api3::Geometry
include Geos::GoogleMaps::ApiCommon::Geometry
# Returns a new LatLngBounds object with the proper LatLngs in place
# for determining the geometry bounds.
def to_g_lat_lng_bounds_api3(options = {})
"new google.maps.LatLngBounds(#{self.lower_left.to_g_lat_lng_api3(options)}, #{self.upper_right.to_g_lat_lng_api3(options)})"
end
# Returns a bounds parameter for the Google Maps API 3 geocoder service.
def to_g_geocoder_bounds_api3(precision = 6)
"#{self.lower_left.to_g_url_value(precision)}|#{self.upper_right.to_g_url_value(precision)}"
end
# Returns a String in Google Maps' LatLngBounds#toString() format.
def to_g_lat_lng_bounds_string_api3(precision = 10)
"((#{self.lower_left.to_g_url_value(precision)}), (#{self.upper_right.to_g_url_value(precision)}))"
end
# Returns a new Polyline.
def to_g_polyline_api3(polyline_options = {}, options = {})
self.coord_seq.to_g_polyline_api3(polyline_options, options)
end
# Returns a new Polygon.
def to_g_polygon_api3(polygon_options = {}, options = {})
self.coord_seq.to_g_polygon_api3(polygon_options, options)
end
# Returns a new Marker at the centroid of the geometry. The options
# Hash works the same as the Google Maps API MarkerOptions class does,
# but allows for underscored Ruby-like options which are then converted
# to the appropriate camel-cased Javascript options.
def to_g_marker_api3(marker_options = {}, options = {})
options = {
:escape => [],
:lat_lng_options => {}
}.merge(options)
opts = Geos::Helper.camelize_keys(marker_options)
opts[:position] = self.centroid.to_g_lat_lng(options[:lat_lng_options])
json = Geos::Helper.escape_json(opts, Geos::GoogleMaps::Api3Constants::UNESCAPED_MARKER_OPTIONS - options[:escape])
"new google.maps.Marker(#{json})"
end
end
module Api3::CoordinateSequence
# Returns a Ruby Array of LatLngs.
def to_g_lat_lng_api3(options = {})
self.to_a.collect do |p|
"new google.maps.LatLng(#{p[1]}, #{p[0]})"
end
end
# Returns a new Polyline. Note that this Polyline just uses whatever
# coordinates are found in the sequence in order, so it might not
# make much sense at all.
#
# The polyline_options Hash follows the Google Maps API arguments to the
# Polyline constructor and include :clickable, :geodesic, :map, etc. See
# the Google Maps API documentation for details.
#
# The options Hash allows you to specify if certain arguments should be
# escaped on output. Usually the options in UNESCAPED_POLY_OPTIONS are
# escaped, but if for some reason you want some other options to be
# escaped, pass them along in options[:escape]. The options Hash also
# passes along options to to_g_lat_lng_api3.
def to_g_polyline_api3(polyline_options = {}, options = {})
options = {
:escape => [],
:lat_lng_options => {}
}.merge(options)
opts = Geos::Helper.camelize_keys(polyline_options)
opts[:path] = "[#{self.to_g_lat_lng_api3(options[:lat_lng_options]).join(', ')}]"
json = Geos::Helper.escape_json(opts, Geos::GoogleMaps::Api3Constants::UNESCAPED_POLY_OPTIONS - options[:escape])
"new google.maps.Polyline(#{json})"
end
# Returns a new Polygon. Note that this Polygon just uses whatever
# coordinates are found in the sequence in order, so it might not
# make much sense at all.
#
# The polygon_options Hash follows the Google Maps API arguments to the
# Polyline constructor and include :clickable, :geodesic, :map, etc. See
# the Google Maps API documentation for details.
#
# The options Hash allows you to specify if certain arguments should be
# escaped on output. Usually the options in UNESCAPED_POLY_OPTIONS are
# escaped, but if for some reason you want some other options to be
# escaped, pass them along in options[:escape]. The options Hash also
# passes along options to to_g_lat_lng_api3.
def to_g_polygon_api3(polygon_options = {}, options = {})
options = {
:escape => [],
:lat_lng_options => {}
}.merge(options)
opts = Geos::Helper.camelize_keys(polygon_options)
opts[:paths] = "[#{self.to_g_lat_lng_api3(options[:lat_lng_options]).join(', ')}]"
json = Geos::Helper.escape_json(opts, Geos::GoogleMaps::Api3Constants::UNESCAPED_POLY_OPTIONS - options[:escape])
"new google.maps.Polygon(#{json})"
end
end
module Api3::Point
# Returns a new LatLng.
def to_g_lat_lng_api3(options = {})
no_wrap = if options[:no_wrap]
', true'
end
"new google.maps.LatLng(#{self.lat}, #{self.lng}#{no_wrap})"
end
# Returns a new Point
def to_g_point_api3(options = {})
"new google.maps.Point(#{self.x}, #{self.y})"
end
end
module Api3::Polygon
include Geos::GoogleMaps::ApiCommon::UrlValueBounds
# Returns a Polyline of the exterior ring of the Polygon. This does
# not take into consideration any interior rings the Polygon may
# have.
def to_g_polyline_api3(polyline_options = {}, options = {})
self.exterior_ring.to_g_polyline_api3(polyline_options, options)
end
# Returns a Polygon of the exterior ring of the Polygon. This does
# not take into consideration any interior rings the Polygon may
# have.
def to_g_polygon_api3(polygon_options = {}, options = {})
self.exterior_ring.to_g_polygon_api3(polygon_options, options)
end
end
module Api3::LineString
include Geos::GoogleMaps::ApiCommon::UrlValueBounds
end
module Api3::GeometryCollection
include Geos::GoogleMaps::ApiCommon::UrlValueBounds
# Returns a Ruby Array of Polylines for each geometry in the
# collection.
def to_g_polyline_api3(polyline_options = {}, options = {})
self.collect do |p|
p.to_g_polyline_api3(polyline_options, options)
end
end
alias_method :to_g_polylines_api3, :to_g_polyline_api3
# Returns a Ruby Array of Polygons for each geometry in the
# collection. If the :single option is set, a single Polygon object will
# be returned with all of the geometries set in the Polygon's "path"
# attribute. You can also use to_g_polygon_single for the same effect.
def to_g_polygon_api3(polygon_options = {}, options = {})
if options[:single]
self.to_g_polygon_single_api3(polygon_options, options)
else
self.collect do |p|
p.to_g_polygon_api3(polygon_options, options)
end
end
end
# Behaves the same as to_g_polygon_api3 with the :single option set, where
# a single Google Maps Polygon will be returned with all of the Polygons
# set in the Polygon's "path" attribute.
def to_g_polygon_single_api3(polygon_options = {}, options = {})
options = {
:escape => [],
:lat_lng_options => {}
}.merge(options)
opts = Geos::Helper.camelize_keys(polygon_options)
opts[:paths] = %{[#{self.collect { |p|
"[#{p.exterior_ring.coord_seq.to_g_lat_lng_api3(options[:lat_lng_options]).join(', ')}]"
}.join(', ')}]}
json = Geos::Helper.escape_json(opts, Geos::GoogleMaps::Api3Constants::UNESCAPED_POLY_OPTIONS - options[:escape])
"new google.maps.Polygon(#{json})"
end
end
end
Geos::GoogleMaps.use_api(3)
|
require 'spec_helper'
describe "Role Type requests" do
describe "GET unpublished /role_type" do
it "should return a 404" do
p = RoleType.make!(:published => false)
get role_type_path(p)
assert_response :missing
end
end
describe "GET published /role_type" do
it "should return a valid page" do
p = RoleType.make!
get role_type_path(p)
assert_response :success
end
end
end
|
FactoryGirl.define do
factory :event do
name { Faker::StarWars.character }
event_date { Date.today }
user
after(:build) do |e|
e.entry_cost = [3.00, 5.00].sample
e.winner_cut = e.entry_cost * 5
e.runner_up_cut = e.entry_cost * 2
e.organizer_cut = e.entry_cost
end
end
end
|
require 'puppetlabs_spec_helper/rake_tasks'
require 'puppet/version'
require 'puppet/vendor/semantic/lib/semantic' unless Puppet.version.to_f < 3.6
require 'puppet-syntax/tasks/puppet-syntax'
# These gems aren't always present, for instance
# on Travis with --without development
begin
require 'puppet_blacksmith/rake_tasks'
rescue LoadError
end
desc "Run acceptance tests"
RSpec::Core::RakeTask.new(:acceptance) do |t|
t.pattern = 'spec/acceptance'
Rake::Task[:spec_prep].execute
end
desc "Populate CONTRIBUTORS file"
task :contributors do
system("git log --format='%aN' | sort -u > CONTRIBUTORS")
end
task :metadata do
sh "metadata-json-lint metadata.json"
end
desc "Run syntax, lint, and spec tests."
task :test => [
:syntax,
:lint,
:spec,
:metadata,
]
|
require 'versatile_rjs/container'
module VersatileRJS
class Page
include Container
def method_missing(name, *args)
if name.to_s =~ /=$/
assign(name, args.first)
else
view.__send__ name, *args
end
end
class ContainerStack < Array
def peek
self[-1]
end
end
attr_reader :view, :stack
private :stack
def initialize(view)
@view = view
@stack = ContainerStack.new
@stack.push self
end
def push_container(container)
stack.push container
end
def pop_container
stack.pop
end
def append_statement(statement)
stack.peek.add_statement statement
statement
end
def <<(statement)
append_statement(ActiveSupport::JSON::Variable.new(statement))
end
def [](id)
VersatileRJS::Proxy::ElementByIdProxy.new_instance(self, id)
end
def select(selector)
VersatileRJS::Proxy::SelectorProxy.new_instance(self, selector)
end
def assign(variable, value)
self << "var #{variable} = #{value.to_json}"
end
def replace_html(id, *args)
self[id].replace_html(*args)
end
def replace(id, *args)
self[id].replace(*args)
end
def insert_html(id, *args)
self[id].insert_html(*args)
end
def remove(id, *args)
self[id].remove(*args)
end
def evaluate(&block)
view.instance_exec(self, &block)
self
end
def execute_rendering(*args_for_rendering)
return '' if args_for_rendering.size == 0
return args_for_rendering.first if args_for_rendering.size == 1 &&
args_for_rendering.first.kind_of?(String)
return render_on_view(*args_for_rendering)
end
def statement_prefix(statement)
"try{" if VersatileRJS.debug_rjs?
end
def statement_suffix(statement)
if VersatileRJS.debug_rjs
<<-EOS
}catch(e){
alert('RJS Error: ' + e);
alert('#{view.__send__(:escape_javascript, statement)}');
throw e;
}
EOS
end
end
private
def render_on_view(*args_for_rendering)
view.instance_eval{render *args_for_rendering}
end
end
end
|
# frozen_string_literal: true
# rubocop:todo all
# Copyright (C) 2020 MongoDB Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
module Mongo
module Auth
class Aws
# Defines behavior around a single MONGODB-AWS conversation between the
# client and server.
#
# @see https://github.com/mongodb/specifications/blob/master/source/auth/auth.rst#mongodb-aws
#
# @api private
class Conversation < SaslConversationBase
# Continue the AWS conversation. This sends the client final message
# to the server after setting the reply from the previous server
# communication.
#
# @param [ BSON::Document ] reply_document The reply document of the
# previous message.
# @param [ Server::Connection ] connection The connection being
# authenticated.
#
# @return [ Protocol::Message ] The next message to send.
def continue(reply_document, connection)
@conversation_id = reply_document[:conversationId]
payload = reply_document[:payload].data
payload = BSON::Document.from_bson(BSON::ByteBuffer.new(payload))
@server_nonce = payload[:s].data
validate_server_nonce!
@sts_host = payload[:h]
unless (1..255).include?(@sts_host.bytesize)
raise Error::InvalidServerAuthConfiguration, "STS host name length is not in 1..255 bytes range: #{@sts_host}"
end
selector = CLIENT_CONTINUE_MESSAGE.merge(
payload: BSON::Binary.new(client_final_payload),
conversationId: conversation_id,
)
build_message(connection, user.auth_source, selector)
end
private
# @return [ String ] The server nonce.
attr_reader :server_nonce
# Get the id of the conversation.
#
# @return [ Integer ] The conversation id.
attr_reader :conversation_id
def client_first_data
{
r: BSON::Binary.new(client_nonce),
p: 110,
}
end
def client_first_payload
client_first_data.to_bson.to_s
end
def wrap_data(data)
BSON::Binary.new(data.to_bson.to_s)
end
def client_nonce
@client_nonce ||= SecureRandom.random_bytes(32)
end
def client_final_payload
credentials = CredentialsRetriever.new(user).credentials
request = Request.new(
access_key_id: credentials.access_key_id,
secret_access_key: credentials.secret_access_key,
session_token: credentials.session_token,
host: @sts_host,
server_nonce: server_nonce,
)
# Uncomment this line to validate obtained credentials on the
# client side prior to sending them to the server.
# This generally produces informative diagnostics as to why
# the credentials are not valid (e.g., they could be expired)
# whereas the server normally does not elaborate on why
# authentication failed (but the reason usually is logged into
# the server logs).
#
# Note that credential validation requires that the client is
# able to access AWS STS. If this is not permitted by firewall
# rules, validation will fail but credentials may be perfectly OK
# and the server may be able to authenticate using them just fine
# (provided the server is allowed to communicate with STS).
#request.validate!
payload = {
a: request.authorization,
d: request.formatted_time,
}
if credentials.session_token
payload[:t] = credentials.session_token
end
payload.to_bson.to_s
end
end
end
end
end
|
require 'rails_helper'
RSpec.describe ImagesController, type: :controller do
describe "GET #new" do
it "renders the :new view" do
get :new
expect(response).to render_template :new
end
end
describe "POST #create" do
context "with valid attributes" do
it "creates a new image" do
expect{
post :create, image: FactoryGirl.attributes_for(:image)
}.to change(Image,:count).by(1)
end
end
context "with invalid attributes" do
it "does not save the new image" do
expect{
post :create, image: FactoryGirl.attributes_for(:invalid_image)
}.to_not change(Image,:count)
end
end
end
end
|
# -*- encoding: utf-8 -*-
Gem::Specification.new do |s|
s.name = "flexmock"
s.version = "0.9.0"
s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version=
s.authors = ["Jim Weirich"]
s.date = "2011-02-27"
s.description = "\n FlexMock is a extremely simple mock object class compatible\n with the Test::Unit framework. Although the FlexMock's\n interface is simple, it is very flexible.\n "
s.email = "jim.weirich@gmail.com"
s.extra_rdoc_files = ["README.rdoc", "CHANGES", "doc/GoogleExample.rdoc", "doc/releases/flexmock-0.4.0.rdoc", "doc/releases/flexmock-0.4.1.rdoc", "doc/releases/flexmock-0.4.2.rdoc", "doc/releases/flexmock-0.4.3.rdoc", "doc/releases/flexmock-0.5.0.rdoc", "doc/releases/flexmock-0.5.1.rdoc", "doc/releases/flexmock-0.6.0.rdoc", "doc/releases/flexmock-0.6.1.rdoc", "doc/releases/flexmock-0.6.2.rdoc", "doc/releases/flexmock-0.6.3.rdoc", "doc/releases/flexmock-0.6.4.rdoc", "doc/releases/flexmock-0.7.0.rdoc", "doc/releases/flexmock-0.7.1.rdoc", "doc/releases/flexmock-0.8.0.rdoc", "doc/releases/flexmock-0.8.2.rdoc", "doc/releases/flexmock-0.8.3.rdoc", "doc/releases/flexmock-0.8.4.rdoc", "doc/releases/flexmock-0.8.5.rdoc", "doc/releases/flexmock-0.9.0.rdoc"]
s.files = ["README.rdoc", "CHANGES", "doc/GoogleExample.rdoc", "doc/releases/flexmock-0.4.0.rdoc", "doc/releases/flexmock-0.4.1.rdoc", "doc/releases/flexmock-0.4.2.rdoc", "doc/releases/flexmock-0.4.3.rdoc", "doc/releases/flexmock-0.5.0.rdoc", "doc/releases/flexmock-0.5.1.rdoc", "doc/releases/flexmock-0.6.0.rdoc", "doc/releases/flexmock-0.6.1.rdoc", "doc/releases/flexmock-0.6.2.rdoc", "doc/releases/flexmock-0.6.3.rdoc", "doc/releases/flexmock-0.6.4.rdoc", "doc/releases/flexmock-0.7.0.rdoc", "doc/releases/flexmock-0.7.1.rdoc", "doc/releases/flexmock-0.8.0.rdoc", "doc/releases/flexmock-0.8.2.rdoc", "doc/releases/flexmock-0.8.3.rdoc", "doc/releases/flexmock-0.8.4.rdoc", "doc/releases/flexmock-0.8.5.rdoc", "doc/releases/flexmock-0.9.0.rdoc"]
s.homepage = "https://github.com/jimweirich/flexmock"
s.rdoc_options = ["--title", "FlexMock", "--main", "README.rdoc", "--line-numbers"]
s.require_paths = ["lib"]
s.rubygems_version = "1.8.10"
s.summary = "Simple and Flexible Mock Objects for Testing"
if s.respond_to? :specification_version then
s.specification_version = 3
if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then
else
end
else
end
end
|
# frozen_string_literal: true
module ActiveStorage
# Provides the class-level DSL for declaring that an Active Record model has attached blobs.
module Attached::Macros
# Specifies the relation between a single attachment and the model.
#
# class User < ActiveRecord::Base
# has_one_attached :avatar
# end
#
# There is no column defined on the model side, Active Storage takes
# care of the mapping between your records and the attachment.
#
# To avoid N+1 queries, you can include the attached blobs in your query like so:
#
# User.with_attached_avatar
#
# Under the covers, this relationship is implemented as a +has_one+ association to a
# ActiveStorage::Attachment record and a +has_one-through+ association to a
# ActiveStorage::Blob record. These associations are available as +avatar_attachment+
# and +avatar_blob+. But you shouldn't need to work with these associations directly in
# most circumstances.
#
# The system has been designed to having you go through the ActiveStorage::Attached::One
# proxy that provides the dynamic proxy to the associations and factory methods, like +attach+.
#
# If the +:dependent+ option isn't set, the attachment will be purged
# (i.e. destroyed) whenever the record is destroyed.
def has_one_attached(name, dependent: :purge_later)
class_eval <<-CODE, __FILE__, __LINE__ + 1
def #{name}
@active_storage_attached_#{name} ||= ActiveStorage::Attached::One.new("#{name}", self, dependent: #{dependent == :purge_later ? ":purge_later" : "false"})
end
def #{name}=(attachable)
#{name}.attach(attachable)
end
CODE
has_one :"#{name}_attachment", -> { where(name: name) }, class_name: "ActiveStorage::Attachment", as: :record, inverse_of: :record
has_one :"#{name}_blob", through: :"#{name}_attachment", class_name: "ActiveStorage::Blob", source: :blob
scope :"with_attached_#{name}", -> { includes("#{name}_attachment": :blob) }
if dependent == :purge_later
after_destroy_commit { public_send(name).purge_later }
end
end
# Specifies the relation between multiple attachments and the model.
#
# class Gallery < ActiveRecord::Base
# has_many_attached :photos
# end
#
# There are no columns defined on the model side, Active Storage takes
# care of the mapping between your records and the attachments.
#
# To avoid N+1 queries, you can include the attached blobs in your query like so:
#
# Gallery.where(user: Current.user).with_attached_photos
#
# Under the covers, this relationship is implemented as a +has_many+ association to a
# ActiveStorage::Attachment record and a +has_many-through+ association to a
# ActiveStorage::Blob record. These associations are available as +photos_attachments+
# and +photos_blobs+. But you shouldn't need to work with these associations directly in
# most circumstances.
#
# The system has been designed to having you go through the ActiveStorage::Attached::Many
# proxy that provides the dynamic proxy to the associations and factory methods, like +#attach+.
#
# If the +:dependent+ option isn't set, all the attachments will be purged
# (i.e. destroyed) whenever the record is destroyed.
def has_many_attached(name, dependent: :purge_later)
class_eval <<-CODE, __FILE__, __LINE__ + 1
def #{name}
@active_storage_attached_#{name} ||= ActiveStorage::Attached::Many.new("#{name}", self, dependent: #{dependent == :purge_later ? ":purge_later" : "false"})
end
def #{name}=(attachables)
#{name}.attach(attachables)
end
CODE
has_many :"#{name}_attachments", -> { where(name: name) }, as: :record, class_name: "ActiveStorage::Attachment", inverse_of: :record
has_many :"#{name}_blobs", through: :"#{name}_attachments", class_name: "ActiveStorage::Blob", source: :blob
scope :"with_attached_#{name}", -> { includes("#{name}_attachments": :blob) }
if dependent == :purge_later
after_destroy_commit { public_send(name).purge_later }
end
end
end
end
|
# frozen_string_literal: true
if ENV.fetch('RACK_MINI_PROFILER', 0).to_i.positive?
# Before uncomment read https://github.com/MiniProfiler/rack-mini-profiler#rails-and-manual-initialization
require 'rack-mini-profiler'
Rack::MiniProfilerRails.initialize!(Rails.application)
end
|
class User < ActiveRecord::Base
has_many :authored_polls,
foreign_key: :author_id,
class_name: :Poll
has_many :responses
end
|
# frozen_string_literal: true
# user_mail.rb
# Author: William Woodruff
# ------------------------
# A Cinch plugin that provides user mailboxes for yossarian-bot.
# ------------------------
# This code is licensed by William Woodruff under the MIT License.
# http://opensource.org/licenses/MIT
require "yaml"
require "fileutils"
require_relative "../yossarian_plugin.rb"
class UserMail < YossarianPlugin
include Cinch::Plugin
use_blacklist
class MboxMessageStruct < Struct.new(:sender, :time, :message)
def to_s
stamp = time.strftime "%H:%M:%S"
"[#{stamp}] <#{sender}> - #{message}"
end
end
def initialize(*args)
super
@mbox_file = File.expand_path(File.join(File.dirname(__FILE__), @bot.server_id, "user_mail.yml"))
if File.file?(@mbox_file)
@mbox = YAML.load_file(@mbox_file, permitted_classes: [MboxMessageStruct, Time, Symbol])
@mbox.default_proc = Proc.new { |h, k| h[k] = [] }
else
FileUtils.mkdir_p File.dirname(@mbox_file)
@mbox = Hash.new { |h, k| h[k] = [] }
end
end
def sync_mbox_file
File.open(@mbox_file, "w+") do |file|
file.write @mbox.to_yaml
end
end
def usage
"!mail <nick> <message> - Send a message to a nick. Messages are delivered the next time the nick speaks."
end
def match?(cmd)
cmd =~ /^(!)?mail$/
end
listen_to :channel
def listen(m)
nick = m.user.nick.downcase
if @mbox.key?(nick)
m.user.send "Here is your mail. Use !mail <nick> <message> to reply in turn."
@mbox[nick].each do |msg|
m.user.send msg.to_s
end
@mbox.delete(nick)
sync_mbox_file
end
end
match /mail (\S+) (.+)/, method: :mail
def mail(m, nick, msg)
if nick.downcase == @bot.nick.downcase
m.reply "That's not going to work.", true
else
@mbox[nick.downcase] << MboxMessageStruct.new(m.user.nick, Time.now, msg)
m.reply "I\'ll give your message to #{nick} the next time I see them.", true
sync_mbox_file
end
end
end
|
begin
require 'jeweler'
Jeweler::Tasks.new do |gemspec|
gemspec.name = "scrapes"
gemspec.summary = "scrape and validate HTML"
#gemspec.description = "A different and possibly longer explanation of"
gemspec.email = "mgarriss@gmail.com"
gemspec.homepage = "http://github.com/mgarriss/scrapes"
gemspec.authors = ["Michael Garriss", "Peter Jones", "Bob Showalter"]
gemspec.add_dependency('hpricot', '>= 0.8.2')
end
rescue LoadError
puts "Jeweler not available. Install it with: gem install jeweler"
end
|
class CreateDeals < ActiveRecord::Migration
def change
create_table :deals do |t|
t.integer :product_id
t.string :serialnum
t.string :productname
t.integer :amount
t.integer :shippingfee
t.string :shippingway
t.string :shippingcode
t.date :paydate
t.string :paytime
t.string :payaccount
t.string :paytype
t.string :status
t.integer :buyer_id
t.string :buyertel
t.string :buyername
t.integer :seller_id
t.string :sellertel
t.timestamps
end
end
end
|
require "rails_helper"
RSpec.describe "new travel plan page", :js do
let(:account) { create_account(onboarding_state: ob_state) }
let(:person) { account.owner }
subject { page }
let(:ob_state) { :complete }
before do
@airports = create_list(:airport, 2)
login_as_account(account)
visit new_travel_plan_path
end
let(:submit_form) { click_button 'Save my travel plan' }
SKIP_LINK = "I don't have specific plans".freeze
context "as part of onboarding survey" do
let(:ob_state) { 'travel_plan' }
it '' do
expect(page).to have_no_sidebar
expect(page).to have_link SKIP_LINK
expect(page).to have_content '1. Travel Plans'
end
example "skipping adding a travel plan" do
expect { click_link SKIP_LINK }.not_to change { TravelPlan.count }
account.reload
expect(account.onboarding_state).to eq "regions_of_interest"
expect(page).to have_selector '.interest-regions-survey'
end
end
context "after onboarding survey" do
let(:ob_state) { 'complete' }
it '' do
expect(page).to have_sidebar
expect(page).to have_no_link SKIP_LINK
expect(page).to have_no_content '1. Travel Plans'
end
end
it_behaves_like 'a travel plan form'
example "showing points estimate table" do
expect(page).to have_no_selector ".PointsEstimateTable"
# choosing two airports
code_0 = @airports[0].code
code_1 = @airports[1].code
fill_in_typeahead("#travel_plan_from", with: code_0, and_choose: code_0)
wait_for_ajax
expect(page).to have_no_selector ".PointsEstimateTable"
fill_in_typeahead("#travel_plan_to", with: code_1, and_choose: code_1)
expect(page).to have_selector ".PointsEstimateTable"
end
describe "filling in the form" do
context "with valid information" do
before do
create_travel_plan(type: :round_trip, account: account)
fill_in_typeahead(
"#travel_plan_from",
with: @airports[0].code,
and_choose: "(#{@airports[0].code})",
)
fill_in_typeahead(
"#travel_plan_to",
with: @airports[1].code,
and_choose: "(#{@airports[1].code})",
)
set_datepicker_field('#travel_plan_depart_on', to: '01/02/2020')
set_datepicker_field('#travel_plan_return_on', to: '01/02/2025')
end
it "creates a travel plan" do
expect { submit_form }.to change { account.travel_plans.count }.by(1)
end
context "when I'm onboarding my first travel plan" do
let(:ob_state) { :travel_plan }
it 'takes me to the next page' do
submit_form
expect(account.reload.onboarding_state).to eq 'account_type'
expect(page).to have_selector '#account_type_forms'
end
end
context "when I'm not on the onboarding survey" do
let(:ob_state) { :complete }
it 'takes me to the travel plans index' do
submit_form
expect(page).to have_selector 'h1', text: /Travel Plans/
end
end
end
example "invalid save" do
# doesn't create a travel plan
expect { submit_form }.not_to change { TravelPlan.count }
# shows me the form again
expect(page).to have_selector 'h2', text: 'Add a Travel Plan'
end
example "with an invalid (non-autocompleted) airport" do # bug fix
fill_in :travel_plan_from, with: 'blah blah blah'
fill_in :travel_plan_to, with: 'not a real code (ZZZ)'
raise if Airport.exists?(code: 'ZZZ') # sanity check
set_datepicker_field('#travel_plan_depart_on', to: '01/02/2020')
set_datepicker_field('#travel_plan_return_on', to: '01/02/2025')
expect { submit_form }.not_to change { TravelPlan.count }
end
end
end
|
# == Schema Information
#
# Table name: stories
#
# id :integer not null, primary key
# title :string(40)
# resume :text
# user_id :integer
# created_at :datetime
# updated_at :datetime
# prelude :text
# cover :string(255)
# cover_file_name :string(255)
# cover_content_type :string(255)
# cover_file_size :integer
# cover_updated_at :datetime
# published :boolean default(FALSE)
# chapter_numbers :integer
# initial_gold :integer default(0)
#
class Story < ActiveRecord::Base
extend FriendlyId
friendly_id :title, use: [:slugged, :finders]
before_destroy :destroy_favorites
has_attached_file :cover, styles: {thumbnail: "200x200>", index_cover: "400x300>"}, :default_url => "no_image_:style.png"
validates :title, presence: true
validates :resume, presence: true
validates :chapter_numbers, presence: true, numericality: true
validates_attachment_size :cover, :less_than => 2.megabytes
validates_attachment_content_type :cover, content_type: ["image/jpg", "image/png", "image/gif", "image/jpeg"]
belongs_to :user
has_many :adventurers, dependent: :destroy
has_many :chapters, dependent: :destroy
has_many :items, dependent: :destroy
has_many :comments
has_many :favorite_stories
has_many :favorited_by, through: :favorite_stories, source: :user
accepts_nested_attributes_for :chapters, reject_if: :all_blank, allow_destroy: true
accepts_nested_attributes_for :items, reject_if: :all_blank, allow_destroy: true
scope :by_user, -> (user_id) { where(user_id: user_id) }
scope :published, -> { where(published: true) }
def weapons
items.weapons
end
def usable_items
items.usable_items
end
def key_items
items.key_items
end
def has_adventurer? adventurers
adventurers.any? {|adventurer| adventurer.story == self}
end
def build_chapters chapter_numbers
for i in (1..chapter_numbers)
chapter = self.chapters.build
chapter.decisions.build
chapter.reference = i
chapter.save
end
end
def self.graph(chapters)
chapters_with_decisions = {
references: chapters.get_references,
chapter_destinies: chapters.get_destinies,
not_used: chapters.get_not_used_references
}
chapters_with_decisions[:valid] = Chapter.validate_chapters(chapters_with_decisions)
chapters_with_decisions
end
def self.search(search)
joins('LEFT JOIN users AS u
ON u.id = stories.user_id').where('u.name LIKE :search
OR stories.title LIKE :search', search: "%#{search}%").order('stories.title ASC') if search
end
def destroy_favorites
favorites_to_destroy = FavoriteStory.where(story_id: self.id)
favorites_to_destroy.destroy_all
end
end
|
# frozen_string_literal: true
require_relative "../standard_exception"
class BadRequestException < StandardException
def initialize(field)
@msg = "The following fields (#{field.join(', ')}) are missing!"
@field = field
super(@msg, @field)
end
end
|
# frozen_string_literal: true
module SC::Billing::Stripe::Webhooks
class BaseOperation < ::SC::Billing::BaseOperation
def self.set_event_type(type_name) # rubocop:disable Naming/AccessorMethodName
define_singleton_method(:event_type) do
type_name
end
end
private
# TODO: refactor
def find_or_raise_user(customer_id)
find_user(customer_id).tap do |user|
raise_if_user_not_found(user, customer_id)
end
end
def find_user(customer_id)
user_model.find(stripe_customer_id: customer_id)
end
def raise_if_user_not_found(user, customer_id)
raise "There is no user with stripe_customer_id: #{customer_id} in system" unless user
end
def run_hook(hook_type, **params)
hook_handler = ::SC::Billing.event_hooks.dig(self.class.event_type, hook_type)
return if hook_handler.nil?
if hook_handler.is_a? Array
hook_handler.each do |hook|
hook.new.call(params)
end
else
hook_handler.new.call(params)
end
end
def run_before_hook(**params)
run_hook('before', params)
end
def run_after_hook(**params)
run_hook('after', params)
end
end
end
|
require "rails_helper"
describe "Set Email Voicemails Mutation API", :graphql do
describe "setEmailVoicemails" do
let(:query) do
<<~'GRAPHQL'
mutation($input: SetEmailVoicemailsInput!) {
setEmailVoicemails(input: $input) {
user {
emailVoicemails
}
}
}
GRAPHQL
end
it "sets email voicemails" do
user = create(:user, email_voicemails: false)
execute query, as: user, variables: {
input: {
emailVoicemails: true,
},
}
expect(user.reload.email_voicemails?).to be(true)
end
end
end
|
require "test/unit"
require_relative "../Lib/challenge1.rb"
class Challenge_1_Test < Test::Unit::TestCase
def test_conversion
input = "49276d206b696c6c696e6720796f757220627261696e206c696b65206120706f69736f6e6f7573206d757368726f6f6d"
expected = "SSdtIGtpbGxpbmcgeW91ciBicmFpbiBsaWtlIGEgcG9pc29ub3VzIG11c2hyb29t"
assert_equal(expected,HexToBase64.hex_to_base64(input))
end
end |
# coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'thematic/version'
Gem::Specification.new do |spec|
spec.name = "thematic"
spec.version = Thematic::VERSION
spec.authors = ["Jay Wengrow"]
spec.email = ["jaywngrw@gmail.com"]
spec.summary = %q{An automated way that prepares HTML/CSS/JS themes for Rails projects.}
spec.description = %q{By running simple commands from the terminal, you can automatically convert regular HTML/CSS/JS themes and have them integrate into your Rails app so that it plays nicely with the asset pipeline.}
spec.homepage = ""
spec.license = "MIT"
spec.files = `git ls-files -z`.split("\x0")
spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) }
spec.test_files = spec.files.grep(%r{^(test|spec|features)/})
spec.require_paths = ["lib"]
spec.add_development_dependency "bundler", "~> 1.7"
spec.add_development_dependency "rake", "~> 10.0"
end
|
# PEDAC
# Problem
# Write a method that takes two arguments: the first is the starting number,
# and the second is the ending number. Print out all numbers between the two numbers
# except if a number is divisible by 3, print "Fizz", if a number is
# divisible by 5, print "Buzz", and finally if a number is divisible by 3 and 5
# print "FizzBuzz".
# Input: two numbers, a starting and ending number
# Output: all number between the two (inclusive) except that:
# numbers divisible by 3 are now "Fizz"
# numbers divisible by 5 are now "Buzz"
# Examples / Test Cases
# fizzbuzz(1, 15) == [1, 2, "Fizz", 4, "Buzz", "Fizz", 7, 8, "Fizz", "Buzz", 11, "Fizz", 13, 14, "FizzBuzz"]
# Data Structures
# Array
# Algorithm
# define a method named 'fizzbuzz' which accepts two integers as parameters
# initiate an array which holds all the numbers between the two input integers, inclusive.
# Iterate through the array, if the element is divisible by 3, replace it with "Fizz"
# if the element is divisble by 5, replace it with "Buzz"
# If the element is divisble by both 3 and five, replace it with "FizzBuzz"
# return the array
# Code
def fizzbuzz(start, finish)
output = (start..finish).to_a.map do |element|
case
when element % 3 == 0 && element % 5 == 0
'FizzBuzz'
when element % 3 == 0
'Fizz'
when element % 5 == 0
'Buzz'
else
element
end
end
output.join(", ")
end
p fizzbuzz(1, 15) #== [1, 2, "Fizz", 4, "Buzz", "Fizz", 7, 8, "Fizz", "Buzz", 11, "Fizz", 13, 14, "FizzBuzz"]
|
require 'spec_helper'
require 'fixtures/data.rb'
shared_examples_for "api request" do
context "CORS requests" do
it "sets the Access-Control-Allow-Origin header to allow CORS from anywhere" do
expect(last_response.headers['Access-Control-Allow-Origin']).to eq('*')
end
it "allows GET HTTP method thru CORS" do
allowed_http_methods = last_response.header['Access-Control-Allow-Methods']
%w{GET}.each do |method| # don't expect we'll need: POST PUT DELETE
expect(allowed_http_methods).to include(method)
end
end
end
end
describe 'api', type: 'feature' do
# app starts up in advance of before :all so for now testing only
# with ./sample-data
after(:all) do
Stretchy.delete 'test-city-data'
#expect(DataMagic.client.indices.get(index: '_all')).to be_empty
end
it "loads the endpoint list" do
get "/endpoints"
expect(last_response).to be_ok
expect(last_response.content_type).to eq('application/json')
result = JSON.parse(last_response.body)
expected = {
'endpoints'=>[
'name'=>'cities',
'url'=>'/cities',
]
}
expect(result).to eq expected
end
it "raises a 404 on missing endpoints" do
get "/missing"
expect(last_response.status).to eq(404)
expect(last_response.content_type).to eq('application/json')
result = JSON.parse(last_response.body)
expected = {
"error"=>404,
"message"=>"missing not found. Available endpoints: cities",
}
expect(result).to eq(expected)
end
describe "data description" do
before do
get '/data.json'
end
it_behaves_like "api request"
it "responds with json" do
expect(last_response).to be_ok
expect(last_response.content_type).to eq('application/json')
end
end
describe "query" do
describe "with one term" do
before do
get '/cities?name=Chicago'
end
it_behaves_like "api request"
it "responds with json" do
expect(last_response).to be_ok
expect(last_response.content_type).to eq('application/json')
result = JSON.parse(last_response.body)
expected = {
"total" => 1,
"page" => 0,
"per_page" => DataMagic::DEFAULT_PAGE_SIZE,
"results" => [
{"state"=>"IL", "name"=>"Chicago", "population"=>2695598,
"land_area"=>227.635, # later we'll make this a float
"location"=>{"lat"=>41.837551, "lon"=>-87.681844}} ]
}
expect(result).to eq(expected)
end
end
describe "with options" do
it "can return a subset of fields" do
get '/cities?state=MA&fields=name,population'
expect(last_response).to be_ok
result = JSON.parse(last_response.body)
expected = {
"total" => 1,
"page" => 0,
"per_page" => DataMagic::DEFAULT_PAGE_SIZE,
"results" => [{"name"=>"Boston", "population"=>617594}]
}
expect(result).to eq(expected)
end
end
describe "with float" do
before do
get '/cities?land_area=302.643'
end
it "responds with json" do
expect(last_response).to be_ok
expect(last_response.content_type).to eq('application/json')
result = JSON.parse(last_response.body)
expected = {
"total" => 1,
"page" => 0,
"per_page" => DataMagic::DEFAULT_PAGE_SIZE,
"results" => [{"state"=>"NY", "name"=>"New York",
"population"=>8175133, "land_area"=>302.643,
"location"=>{"lat"=>40.664274, "lon"=>-73.9385}}]
}
expect(result).to eq(expected)
end
end
describe "near zipcode" do
before do
get '/cities?zip=94132&distance=30mi'
# why isn't SF, 30 miles from SFO... maybe origin point is not
# where I expect
end
it "can find an attribute from an imported file" do
expect(last_response).to be_ok
result = JSON.parse(last_response.body)
result["results"] = result["results"].sort_by { |k| k["name"] }
expected = {
"total" => 2,
"page" => 0,
"per_page" => DataMagic::DEFAULT_PAGE_SIZE,
"results" => [
{"state"=>"CA", "name"=>"Fremont", "population"=>214089, "land_area"=>77.459, "location"=>{"lat"=>37.494373, "lon"=>-121.941117}},
{"state"=>"CA", "name"=>"Oakland", "population"=>390724, "land_area"=>55.786, "location"=>{"lat"=>37.769857, "lon"=>-122.22564}}]
}
expect(result).to eq(expected)
end
end
describe "with sort" do
it "can sort numbers ascending" do
get '/cities?sort=population:asc'
expect(last_response).to be_ok
response = JSON.parse(last_response.body)
expect(response["results"][0]['name']).to eq("Rochester")
end
end
end
end
|
Pod::Spec.new do |s|
# βββ Spec Metadata ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ #
s.name = "JCVideoPlayer"
s.version = "1.0.3"
s.summary = "iOS Framework to manage and play videos."
s.description = <<-DESC
iOS Framework to manage and play videos and customize the video player.
DESC
s.homepage = "https://github.com/jmcur/JCVideoPlayer.git"
# s.screenshots = "www.example.com/screenshots_1.gif", "www.example.com/screenshots_2.gif"
# βββ Spec License βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ #
s.license = { :type => "MIT", :file => "LICENSE" }
# βββ Author Metadata βββββββββββββββββββββββββββββββββββββββββββββββββββββββββ #
s.author = { "Juan Curti" => "juancurti22@gmail.com" }
# βββ Platform Specifics βββββββββββββββββββββββββββββββββββββββββββββββββββββββ #
s.platform = :ios
s.ios.deployment_target = "8.0"
# βββ Source Location ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ #
s.source = { :git => "https://github.com/jmcur/JCVideoPlayer.git", :tag => "#{s.version}" }
# βββ Source Code ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ #
s.source_files = "JCVideoPlayer/**/*.{h,m,swift}"
# βββ Resources ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ #
s.resources = "JCVideoPlayer/**/*.{xib,xcassets,xib,png,json}"
# βββ Project Linking ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ #
s.framework = "UIKit"
s.framework = "AVFoundation"
s.framework = "AVKit"
s.framework = "Foundation"
# βββ Project Settings βββββββββββββββββββββββββββββββββββββββββββββββββββββββββ #
s.requires_arc = true
s.dependency 'Alamofire', '~> 4.4'
s.dependency 'SwiftGifOrigin', '~> 1.6.1'
s.pod_target_xcconfig = { 'SWIFT_VERSION' => '3' }
end
|
module DeviseHelpers
def as_user(user=nil)
current_user = user || Fabricate(:user)
if request.present?
sign_in(current_user)
else
login_as(current_user, :scope => :user)
end
request.env['devise.mapping'] = Devise.mappings[:user]
yield if block.present?
return self
end
def as_visitor(user=nil, &block)
current_user = user || Fabricate.stub(:user)
if request.present?
sign_out(current_user)
else
logout(:user)
end
block.call if block.present?
return self
end
end
RSpec.configure do |config|
config.extend DeviseHelpers
end
|
class Item < ActiveRecord::Base
validates_presence_of :name, uniqueness: true
has_many :recipes
has_many :resources, through: :recipes
mount_uploader :image, PictureUploader
end
|
module KMP3D
class BinaryWriter
attr_accessor :bytes
def initialize(path=nil)
@path = path
@bytes = ""
end
def write_to_file
File.open(@path, "wb") { |f| f.write(@bytes) }
end
def head
@bytes.length
end
def write(data)
@bytes += data
end
def write_byte(data)
@bytes += [Data.hexify(data)].pack("C")
end
def write_uint16(data)
@bytes += [Data.hexify(data)].pack("S").reverse
end
def write_int16(data)
@bytes += [Data.hexify(data)].pack("s").reverse
end
def write_uint32(data)
@bytes += [Data.hexify(data)].pack("L").reverse
end
def write_float(data)
@bytes += [data.to_f].pack("F").reverse
end
def write_vector3d(data)
write_float(data.x)
write_float(data.z)
write_float(-data.y)
end
def write_position(data)
write_vector3d(data.to_a.map { |c| c.to_m })
end
def write_csv_float(data)
data.split(",").each { |f| write_float(f) }
end
def insert_uint32(pos, data)
@bytes[pos, 4] = [Data.hexify(data)].pack("L").reverse
end
end
end
|
require 'rails_helper'
# Specs in this file have access to a helper object that includes
# the PatientsHelper. For example:
#
# describe PatientsHelper do
# describe "string concat" do
# it "concats two strings with spaces" do
# expect(helper.concat_strings("this","that")).to eq("this that")
# end
# end
# end
RSpec.describe PatientsHelper, type: :helper do
pending "add some examples to (or delete) #{__FILE__}"
context '#update_pagination_partial_path' do
it "returns an update_pagination partial's path" do
patients = double('patients', :next_page => 2)
assign(:patients, patients)
expect(helper.update_pagination_partial_path).to(
eq 'patients/patients_pagination_page/update_pagination'
)
end
it "returns a remove_pagination partial's path" do
patients = double('patients', :next_page => nil)
assign(:patients, patients)
expect(helper.update_pagination_partial_path).to(
eq 'patients/patients_pagination_page/remove_pagination'
)
end
end
end
|
class AddLonToMuseum < ActiveRecord::Migration
def change
add_column :museums, :lon, :float
end
end
|
class Relation < ActiveRecord::Base
belongs_to :article, class_name: "Article"
belongs_to :tag, class_name: "Tag"
end
|
# frozen_string_literal: true
# rubocop:todo all
require 'spec_helper'
describe 'Connection pool stress test' do
require_stress
let(:options) do
{ max_pool_size: 5, min_pool_size: 3 }
end
let(:thread_count) { 5 }
let(:documents) do
[].tap do |documents|
10000.times do |i|
documents << { a: i}
end
end
end
let(:operation_threads) do
[].tap do |threads|
thread_count.times do |i|
threads << Thread.new do
100.times do |j|
collection.find(a: i+j).to_a
sleep 0.1
collection.find(a: i+j).to_a
end
end
end
end
end
let(:client) do
authorized_client.with(options)
end
let(:collection) do
client[authorized_collection.name].tap do |collection|
collection.drop
collection.insert_many(documents)
end
end
shared_examples_for 'does not raise error' do
it 'does not raise error' do
collection
expect {
threads.collect { |t| t.join }
}.not_to raise_error
end
end
describe 'when several threads run operations on the collection' do
let(:threads) { operation_threads }
context 'min pool size 0, max pool size 5' do
let(:options) do
{ max_pool_size: 5, min_pool_size: 0 }
end
let(:thread_count) { 7 }
it_behaves_like 'does not raise error'
end
context 'min pool size 1, max pool size 5' do
let(:options) do
{ max_pool_size: 5, min_pool_size: 1 }
end
let(:thread_count) { 7 }
it_behaves_like 'does not raise error'
end
context 'min pool size 2, max pool size 5' do
let(:options) do
{ max_pool_size: 5, min_pool_size: 2 }
end
let(:thread_count) { 7 }
it_behaves_like 'does not raise error'
end
context 'min pool size 3, max pool size 5' do
let(:options) do
{ max_pool_size: 5, min_pool_size: 3 }
end
let(:thread_count) { 7 }
it_behaves_like 'does not raise error'
end
context 'min pool size 4, max pool size 5' do
let(:options) do
{ max_pool_size: 5, min_pool_size: 4 }
end
let(:thread_count) { 7 }
it_behaves_like 'does not raise error'
end
context 'min pool size 5, max pool size 5' do
let(:options) do
{ max_pool_size: 5, min_pool_size: 5 }
end
let(:thread_count) { 7 }
it_behaves_like 'does not raise error'
end
end
describe 'when there are many more threads than the max pool size' do
let(:threads) { operation_threads }
context '10 threads, max pool size 5' do
let(:thread_count) { 10 }
it_behaves_like 'does not raise error'
end
context '15 threads, max pool size 5' do
let(:thread_count) { 15 }
it_behaves_like 'does not raise error'
end
context '20 threads, max pool size 5' do
let(:thread_count) { 20 }
it_behaves_like 'does not raise error'
end
context '25 threads, max pool size 5' do
let(:thread_count) { 25 }
it_behaves_like 'does not raise error'
end
end
end
|
# frozen_string_literal: true
# For collecting information from the contact form
class ContactResponse < ApplicationRecord
validates :name, :email, :message, presence: true
def self.by_ip_address(ip)
where(ip_address: ip).last
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 rails db:seed command (or created alongside the database with db:setup).
#
# Examples:
#
# movies = Movie.create([{ name: 'Star Wars' }, { name: 'Lord of the Rings' }])
# Character.create(name: 'Luke', movie: movies.first)
Student.destroy_all
Instructor.destroy_all
i1 = Instructor.create("Mike")
i2 = Instructor.create("Bob")
i3 = Instructor.create("Carl")
i4 = Instructor.create("Steve")
s1 = Student.create(name: "Mary", major: "Med School", age: "27")
s2 = Student.create(name: "Beth", major: "Old School", age: "28")
s3 = Student.create(name: "Carla", major: "High School", age: "29")
s4 = Student.create(name: "Tina", major: "Ranger School", age: "22")
P " SSSSSEEEEEEEDDDDDDDEEEEEEEEEDDDDDDDEEEEEEEEDDDDDDDDDDDDD+++++++++++" |
class Bitmap
def initialize(width, height)
@width = width.to_i
@height = height.to_i
@pixels = create_pixels(@width, @height)
end
def create_pixels(width, height)
if out_of_bounds?(width) || out_of_bounds?(height)
raise StandardError, 'Bitmap dimensions out of bounds'
end
Array.new(height) { Array.new(width, 'O') }
end
def format_pixels
@pixels.map(&:join).join("\n")
end
def clear
@pixels.map { |row| row.fill('O') }
end
def magic_fill(x, y, colour)
x = x.to_i
y = y.to_i
if out_of_bounds?(x, @width) || out_of_bounds?(y, @height)
raise StandardError, 'Pixel out of bounds'
end
current_colour = get_pixel_colour(x, y)
pixels_to_fill = [[x, y]]
while pixel = pixels_to_fill.shift
set_pixel_colour(*pixel, colour)
pixels_to_fill += find_pixels_to_colour(*pixel, current_colour)
pixels_to_fill.uniq!
end
end
def find_pixels_to_colour(x, y, current_colour)
pixels_to_fill = []
adjacent_pixels = get_adjacent_pixels_for_pixel(x, y)
pixels = adjacent_pixels.map do |pixel|
pixels_to_fill << pixel if is_in_magic_area?(*pixel, current_colour)
end
pixels_to_fill
end
def get_adjacent_pixels_for_pixel(x, y)
[[x - 1, y], [x + 1, y], [x, y - 1], [x, y + 1]]
end
def is_in_magic_area?(x, y, current_colour)
if !out_of_bounds?(x, @width) && !out_of_bounds?(y, @height)
get_pixel_colour(x, y) == current_colour
end
end
def set_horizontal_segment_colour(x1, x2, y, colour)
x1 = x1.to_i
x2 = x2.to_i
y = y.to_i
if out_of_bounds?(x1, @width) || out_of_bounds?(x2, @width) ||
out_of_bounds?(y, @height)
raise StandardError, 'Segment out of bounds'
end
@pixels[y - 1].fill(colour, (x1 - 1)..(x2 - 1))
end
def set_vertical_segment_colour(x, y1, y2, colour)
x = x.to_i
y1 = y1.to_i
y2 = y2.to_i
if out_of_bounds?(x, @width) || out_of_bounds?(y2, @height) ||
out_of_bounds?(y2, @height)
raise StandardError, 'Segment out of bounds'
end
@pixels[(y1 - 1)..(y2 - 1)].map { |row| row[x - 1] = colour }
end
def get_pixel_colour(x, y)
# TODO Check bounds
@pixels[y - 1][x - 1]
end
def set_pixel_colour(x, y, colour)
x = x.to_i
y = y.to_i
if out_of_bounds?(x, @width) || out_of_bounds?(y, @height)
raise StandardError, "Pixel #{x}, #{y} doesn't exist in bitmap"
end
@pixels[y - 1][x - 1] = colour
end
private
def out_of_bounds?(dimension, max = 250)
dimension < 1 || dimension > max
end
end
|
class OldDescription < ActiveRecord::Base
belongs_to :recommendation
validates_presence_of :originally_created_at
validates_presence_of :description
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.