text stringlengths 10 2.61M |
|---|
require 'rails_helper'
RSpec.describe 'admin logs in' do
it 'sees admin tools in navbar' do
admin_logs_in
visit root_path
expect(page).to have_content('Admin Tools')
expect(page).to_not have_content('Moderator Tools')
end
end
|
require_relative '../test_case'
module RackRabbit
class TestSignals < TestCase
#--------------------------------------------------------------------------
def test_pop_is_fifo_queue
signals = Signals.new
signals.push(:TTIN)
signals.push(:TTOU)
signals.push(:QUIT)
assert_equal(:TTIN, signals.pop)
assert_equal(:TTOU, signals.pop)
assert_equal(:QUIT, signals.pop)
end
#--------------------------------------------------------------------------
def test_pop_blocks_when_queue_is_empty
signals = Signals.new
thread = Thread.new { sleep 0.1 ; signals.push :QUIT }
seconds = measure do
sig = signals.pop
assert_equal(:QUIT, sig)
end
assert_equal(true, seconds >= 0.1, 'verify we blocked for > 100ms')
thread.join
end
#--------------------------------------------------------------------------
def test_pop_blocking_can_be_timed_out
signals = Signals.new
seconds = measure do
sig = signals.pop(:timeout => 0.1)
assert_equal(:timeout, sig)
end
assert_equal(true, seconds >= 0.1, 'verify we blocked for > 100ms')
end
#--------------------------------------------------------------------------
end # class TestSignals
end # module RackRabbit
|
class SearchController < ApplicationController
skip_before_action :authenticate_user!
skip_authorization_check
before_action :load_query, :find_target, only: :search
def search
@result = ThinkingSphinx.search(@query, classes: [@target])
end
private
def find_target
models ={ answers: Answer, questions: Question, comments: Comment, users: User, everywhere: ThinkingSphinx}
@target = models[params[:search][:target].to_sym]
end
def load_query
@query = params[:search][:query]
end
end
|
class ApplicationController < ActionController::Base
rescue_from Pundit::NotAuthorizedError, with: :user_not_authorized
include Pundit
def user_not_authorized
flash[:warning] = "You are not authorized to perform this action."
redirect_to(request.referrer || root_path)
end
end
|
#spec/connectfour_spec.rb
require 'connectfour.rb'
require 'spec_helper.rb'
describe Player do
let(:player_one){ Player.new("player_one", 1) }
let(:player_two){ Player.new("player_two", 2) }
describe "#name" do
it "returns each player's name" do
expect(player_one.name).to eql("player_one")
expect(player_two.name).to eql("player_two")
end
end
describe "#disc" do
it "assigns each player a unique color" do
expect(player_one.disc).to eql("\u2B24".yellow)
expect(player_two.disc).to eql("\u2B24".red)
end
end
end
describe Board do
let(:empty_board) { Board.new }
let(:p1) { "\u2B24".yellow }
let(:p2) { "\u2B24".red }
let(:draw_board) { Board.new([[p2,p1,p2,p1,p2,p1,p2],
[p2,p2,p1,p1,p2,p2,p1],
[p1,p2,p1,p1,p1,p2,p1],
[p1,p2,p1,p2,p2,p1,p2],
[p1,p1,p2,p2,p2,p1,p2],
[p2,p1,p1,p2,p1,p2,p1]]) }
let(:horizontal_board) { Board.new([[p2,p1,p2,p1,p2,p1,p2],
[p2,p2,p1,p1,p2,p2,p1],
[p1,p2,p1,p1,p1,p2,p1],
[p1,p2,p1,p2,p2,p1,p2],
[p1,p1,p2,p2,p2,p1,p2],
[p2,p1,p1,p2,p2,p2,p2]]) }
let(:vertical_board) { Board.new([[p2,p1,p2,p1,p2,p1,p2],
[p2,p2,p2,p1,p2,p2,p1],
[p1,p2,p1,p1,p1,p2,p1],
[p1,p2,p1,p2,p1,p1,p2],
[p1,p1,p2,p2,p1,p1,p2],
[p2,p1,p1,p2,p1,p2,p1]]) }
let(:diagonal_board) { Board.new([[p2,p1,p2,p1,p2,p1,p2],
[p2,p2,p1,p1,p2,p2,p1],
[p1,p2,p1,p1,p1,p2,p1],
[p1,p2,p2,p2,p2,p1,p2],
[p1,p1,p2,p2,p2,p1,p2],
[p2,p1,p1,p2,p1,p2,p1]]) }
describe "#create_board" do
it "creates an array of arrays" do
expect(empty_board.create_board).to eql(empty_board.current_board)
end
end
describe "#victory?" do
it "correctly awards a victory to the winning player" do
4.times {empty_board.drop_disc(0, p1)}
expect(empty_board.victory?).to be true
end
end
describe "#draw?" do
context "if all squares are filled and nobody has achieved victory" do
it "ends the game in a draw" do
expect(draw_board.draw?).to be true
end
end
end
describe "#check_horizontally" do
it "ends the game if a player gets four in a row horizontally" do
expect(horizontal_board.check_horizontally).to eql(p2)
end
end
describe "#check_vertically" do
it "ends the game if a player gets four in a row vertically" do
expect(vertical_board.check_vertically).to eql(p1)
end
end
describe "#check_diagonally" do
it "ends the game if a player gets four in a row diagonally" do
expect(diagonal_board.check_diagonally).to eql(p2)
end
end
end |
class CheckBacklinkJob < ActiveJob::Base
queue_as :default
def perform(backlink)
page_body = HTTParty.get(backlink.referrer_page).body
doc = Nokogiri::HTML(page_body)
link_exists = doc.css('a').any? do |link|
link.attr(:href) =~ /#{backlink.referent_domain}/
end
backlink.set_active(link_exists)
end
end
|
#!/usr/bin/ruby
require 'pathname'
require 'tempfile'
require 'libreconv'
class Libreconv::Converter
def command_env
# HACK: TZ を渡さないとUTCで日付評価されてしまう
Hash[%w[TZ HOME PATH LANG LD_LIBRARY_PATH SYSTEMROOT TEMP].map { |k| [k, ENV[k]] }]
end
end
class Converter
def self.convert(input_file, output_file, convert_type='pdf')
if File.directory? output_file
output_dir = Pathname.new(output_file)
output_file = output_dir + "#{File.basename(input_file, '.*')}.#{convert_type}"
else
output_dir = File.basename(output_file)
end
tmp_file = Tempfile.create('__', output_dir).path
Libreconv.convert(input_file, tmp_file, nil, convert_type)
File.rename(tmp_file, output_file)
end
end
|
class Cockatrice < Formula
desc "Cross-platform virtual tabletop for multiplayer card games"
homepage "https://cockatrice.github.io/"
url "https://github.com/Cockatrice/Cockatrice.git",
:tag => "2018-04-16-Release-2.5.1",
:revision => "1fbdea0f35c25313e7cf481b98552c92cc70a6ec"
version "2.5.1"
version_scheme 1
head "https://github.com/Cockatrice/Cockatrice.git"
bottle do
sha256 "c42f80f3269a7226b40e52cf3af6be44b3952882c2d0c235b536120552c9d550" => :high_sierra
sha256 "67373a44512d250598df6cbe3f29c121c54519ea55233635f0d7991eee522f7c" => :sierra
sha256 "6caa34c3b0aed2e8451637eea27bc0f819924bec2d07bb22b7919730246d1b05" => :el_capitan
end
depends_on :macos => :el_capitan
depends_on "cmake" => :build
depends_on "protobuf"
depends_on "qt"
fails_with :clang do
build 503
cause "Undefined symbols for architecture x86_64: google::protobuf"
end
def install
mkdir "build" do
system "cmake", "..", *std_cmake_args
system "make", "install"
prefix.install Dir["release/*.app"]
end
end
test do
assert_predicate prefix/"cockatrice.app/Contents/MacOS/cockatrice", :executable?
assert_predicate prefix/"oracle.app/Contents/MacOS/oracle", :executable?
end
end
|
class RenameTimeIdColumnToSessionId < ActiveRecord::Migration
def change
rename_column :sanctuaries_times, :time_id, :session_id
end
end
|
Rails.application.routes.draw do
root 'boats#index'
get ':user_name', to: 'profiles#show', as: :profile
get ':user_name/edit', to: 'profiles#edit', as: :edit_profile
patch ':user_name/edit', to: 'profiles#update', as: :update_profile
devise_for :users, :controllers => { registrations: 'registrations' }
resources :boats
resources :jobs
resources :users
# For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
end
|
# -*- coding: utf-8 -*-
require 'colorize'
require 'charlock_holmes'
def check_templates(path, color = true)
fail Errno::ENOENT unless File.exist?(path)
if File.ftype(path) == 'directory'
check_folder(path, color)
else
check_file(path, color)
end
rescue Errno::ENOENT
puts_warn "#{format(get_message(:NO_EXIST_1), path)}", color
false
rescue Errno::EACCES
puts_warn "#{format(get_message(:NO_ACCESS_1), path)}", color
false
rescue => ex
puts ex.backtrace
puts_warn "#{format(get_message(:ERROR_3), path, ex.class, ex)}", color
false
end
def check_folder(path, color)
ans = true
Dir.glob("#{path}/**/*").sort.each do |f|
if File.ftype(f) == 'file'
ret = check_file(f, color)
ans = false unless ret
end
end
ans
end
def check_file(path, color)
fail Errno::ENOENT unless File.exist?(path)
src = File.read(path)
detection = CharlockHolmes::EncodingDetector.detect(src)
# puts "#{detection[:encoding]} #{detection[:type]} #{path}"
fail(ArgumentError, format(get_message(:BAD_TYPE_1), detection[:type])) if detection[:type] != :text
fail(ArgumentError, format(get_message(:BAD_ENCODING_1), detection[:encoding])) if detection[:encoding] != 'UTF-8'
parser = TemplateParser::Parser.new
template = parser.parse(src)
# puts template
true
rescue Errno::ENOENT
puts_warn "#{format(get_message(:NO_EXIST_1), path)}", color
false
rescue Errno::EACCES
puts_warn "#{format(get_message(:NO_ACCESS_1), path)}", color
false
rescue ArgumentError => ex
puts_warn "#{format(ex.message, path)}", color
false
rescue Racc::ParseError => ex
puts_warn "#{format(ex.message, path)}", color
false
rescue => ex
puts_warn "#{format(get_message(:ERROR_3), path, ex.class, ex)}", color
false
end
def sample_template
<<"EOS"
TYPE: type-0
SUBJ: メールのタイトル
FROM: my@example.com
TO: to_001@example.com
TO: to_002@example.com
CC: cc_001@example.com
CC: cc_002@example.com
BCC: bcc_001@example.com
BCC: bcc_002@example.com
BODY:
メールの本文
EOS
end
def write_template(path, color)
begin
fail Errno::EEXIST if File.exist?(path)
open(path, 'w') { |f| f.write sample_template }
rescue Errno::EEXIST
puts_warn "#{format(get_message(:EXIST_1), path)}", color
false
rescue Errno::ENOENT
puts_warn "#{format(get_message(:NO_ACCESS_1), path)}", color
false
rescue Errno::EACCES
puts_warn "#{format(get_message(:NO_ACCESS_1), path)}", color
false
rescue => ex
puts ex.backtrace
puts_warn "#{format(get_message(:ERROR_3), path, ex.class, ex)}", color
false
end
true
end
# stdout へ出力する
def puts_warn(str, color = true)
if color
color_opt = { color: :red }
warn str.colorize(color_opt)
else
warn str
end
end
|
class Ipsum < ActiveRecord::Base
validates :theme, :presence => true
validates :motto, :presence => true
validates :phrases, :presence => true
end
|
require_relative '../action'
class Screenplay
module Actions
# @todo source: lets you point to a URL instead of using on_fail
class Yum < Screenplay::Action
def initialize(
package: nil,
state: :installed,
update_cache: false,
upgrade: false,
sudo: false,
on_fail: nil
)
@package = package
@on_fail = on_fail
action = case state
when :latest then 'install'
# install should just check to see if it's installed, not always install it
when :installed then 'install'
when :removed then 'remove'
end
commands = []
commands << 'yum upgrade -y' if upgrade
commands << 'yum update -y' if update_cache
commands << "yum #{action} -y #{package}" if package
commands.map! { |c| "sudo #{c}" } if sudo
command = commands.size == 1 ? commands.first : commands.join(' && ')
super(command)
end
def perform(hostname)
result = Screenplay::Environment.hosts[hostname].ssh.run(@command)
return result if result.exception?
result.status = case result.exit_code
when 0
stdout = result.stdout
if stdout.match(/Installed:\s+#{@package}/)
:updated
else
:no_change
end
else
handle_on_fail
:failed
end
result
end
end
end
end
|
require 'rails_helper'
describe 'admin/case_study_gallery_images/edit' do
let(:title) { 'Short' }
let(:case_study_gallery_image) do
create(:case_study_gallery_image,
title: title)
end
before do
assign(:case_study_gallery_image, case_study_gallery_image)
render
end
it 'renders the page title' do
expect(rendered).to match(/Edit\n'#{case_study_gallery_image.title}'/)
end
it 'renders the case study form' do
expect(rendered).to match(/Save/)
end
context 'with a long title' do
let(:title) { 'Give Cat - The Bookmarklet you never knew you needed!' }
it 'concatenates after X number of characters' do
expect(rendered).to match(/Edit\n'Give Ca...'/)
end
end
describe 'form fields' do
let(:title) { 'Give Cat' }
let(:case_study_gallery_image) do
create(:case_study_gallery_image,
title: title)
end
it 'renders the title' do
expect(rendered).to match(/value="#{title}"/)
end
context 'with an image' do
file = File.join(Rails.root, 'spec', 'support', 'files', 'mega_fone.png')
let(:image) { Rack::Test::UploadedFile.new(file) }
let(:case_study_gallery_image) do
create(:case_study_gallery_image,
title: title,
image: image)
end
it 'renders the header image' do
expect(rendered).to match(/mega_fone.png/)
end
end
end
end
|
module ApplicationHelper
def page_header(title, tag='h1')
content_tag(:div, :class => 'page-header') do
content_tag(tag.to_sym, title)
end
end
def app
@app ||= App.default
end
end
|
FactoryGirl.define do
factory :service_request do
protocol nil
trait :with_protocol do
protocol factory: :protocol_imported_from_sparc
end
factory :service_request_with_protocol, traits: [:with_protocol]
end
end
|
class Contact < ApplicationRecord
belongs_to :user
belongs_to :contact, class_name: 'User'
validates_uniqueness_of :user_id, scope: :contact_id
def self.find_by_users(user_id, contact_id)
where('user_id = ? AND contact_id = ?', user_id, contact_id).or(
where('user_id = ? AND contact_id = ?', contact_id, user_id)
)[0]
end
end
|
require 'aws-sdk'
require 'aws-base'
# Registered entity
# This entity is saved totally under
class RegisteredEntity < AWSBase
DEVICE_INFO_DB = "DevicePathInfoDB"
DEVICE_COLUMN_NAME = "DeviceRegId"
attr_reader :db
def initialize
super # call super to setup for AWS
# Find the db that saves the devices info
@db = AWS::SimpleDB.new.domains.create(DEVICE_INFO_DB)
end
def add_device_for_path path, device_id
devices = @db.items[path].attributes[DEVICE_COLUMN_NAME]
devices.add device_id unless devices.include? device_id
end
def delete_device_for_path path, device_id
devices = @db.items[path].attributes[DEVICE_COLUMN_NAME]
devices.delete device_id if devices.include? device_id
end
def list
list = {}
@db.items.each {|path| list[path.name] = path.attributes[DEVICE_COLUMN_NAME].values}
JSON.dump list
end
end
|
module Concerns::WebMonitor::Validation
extend ActiveSupport::Concern
included do
attr_accessor :password_confirmation
validates :name, presence: true
validates :login,
presence: true,
uniqueness: { scope: :genre_id },
length: { in: 3..20 }
validates :password,
presence: true,
length: { in: 6..12 },
confirmation: true,
if: :password_validation_required?
validates :password_confirmation,
presence: true,
if: :password_validation_required?
validate :login_changed_validation, if: :persisted?
before_validation :undo_password, unless: :password_change_tried?, on: :update
private
def password_validation_required?
new_record? ||
(password_changed? || password_confirmation.present?)
end
def password_change_tried?
password.present? || password_confirmation.present?
end
def undo_password
self.password = password_was
end
def login_changed_validation
if login_changed? && !password_changed?
errors.add(:base, :login_changed)
end
end
end
end
|
require 'spec_helper'
require 'byebug'
require 'fixtures/default_test'
describe Ddoc do
let :fixtures do
File.dirname(__FILE__) + '/fixtures'
end
let :expected do
File.read(fixtures + "/#{test_name}_expected.ddoc.rb")
end
let :result do
File.read(fixtures + "/#{test_name}_result.ddoc.rb")
end
context 'Default options' do
let(:test_name) { 'default' }
before do
TestClass.class_method
TestClass.new('foo').instance_method_with_args(7)
end
it "doesn't break return values" do
expect(TestClass.new('foo').instance_method_with_args(7)).to eq [7]
end
it 'generates correct documentation' do
expect(result).to eq expected
end
end
end
|
class PostsController < ApplicationController
before_action :set_post, only: %i[edit update destroy]
def index
@posts = current_user.posts
end
def post_hot
@posts = Post.where(view: :desc)
end
def post_new
@posts = Post.where(created_at: :desc)
end
def show
@post = Post.find_by(id: params[:id])
if @post.nil?
flash[:error] = 'không tìm thấy bài viết, vui lòng kiểm tra lại'
redirect_to root_path
end
end
def new
@post = Post.new
end
def create
post = current_user.posts.new(post_params)
if post.save
flash[:success] = 'ok'
redirect_to new_post_path
else
flash[:error] = 'co loi'
render :new
end
end
def destroy
if @post.destroy
flash[:success] = 'ok'
else
flash[:error] = 'co loi'
end
redirect_to posts_path
end
def edit; end
def update
if @post.update(post_params)
flash[:success] = 'ok'
else
flash[:error] = 'co loi'
end
render :edit
end
private
def set_post
@post = current_user.posts.find_by(id: params[:id])
end
def post_params
params.require(:post).permit(:name, :image_title ,:description)
end
end
|
class ProductsController < ApplicationController
def index
@products = Product.page(params[:page]).per(20)
end
end
|
class ApplicationController < ActionController::Base
# Prevent CSRF attacks by raising an exception.
# For APIs, you may want to use :null_session instead.
protect_from_forgery with: :exception
def index
render text: 'DUMMY APP'
end
def default_url_options
{ locale: 'en' }
end
protected
def extra_ability_parameters
{}
end
end
|
class BoardsController < ApplicationController
include UsersHelper
include PostsHelper
include BoardsHelper
def show
@board = Board.first
# refactor sql query, right now orders by sum(value) then updated_at, also assuming all posts are associated with the first board, and all comments are for post, group by just v.votable_id (ok in sql but not pg) is faster
# coalesce because postgres does not return sum of empty column
@posts = Post.find_by_sql("
select p.*, v.votable_id, count(v.votable_id) as votes_count, coalesce(sum(v.value),0) as votes_value_sum
from posts p
left join votes v on p.id = v.votable_id
group by p.id, v.votable_id
order by votes_value_sum desc, p.updated_at desc")
# only way to get includes to work on the array returned from the sql statement above, maybe refactor don't need all followers information
ActiveRecord::Associations::Preloader.new.preload(@posts, [:owner, :comments, {comments: :owner}, :followers])
if user_count_unread_posts(current_user) > 0
@notification = user_first_unread_post(current_user)
# maybe refactor this and chat_room_mark_read to notification_mark_read, and delete notification
post_mark_read(@notification)
end
# maybe refactor later, only update user if he/she is viewing unread posts, add +1 to current user due to delay in updating associations through touch
if board_has_unread?(@board)
board_mark_read(@board)
end
end
end
|
class PetsController < ApplicationController
before_action :set_pet, only: [:show, :update, :destroy]
# GET /pets
def index
@pets = Pet.all
render json: @pets
end
# GET /pets/1
def show
render json: @pet
end
# POST /pets
def create
@pet = Pet.new(pet_params)
if @pet.save
render json: @pet, status: :created, location: @pet
else
render json: @pet.errors, status: :unprocessable_entity
end
end
# PATCH/PUT /pets/1
def update
if @pet.update(pet_params)
render json: @pet
else
render json: @pet.errors, status: :unprocessable_entity
end
end
# DELETE /pets/1
def destroy
@pet.destroy
end
private
# Use callbacks to share common setup or constraints between actions.
def set_pet
@pet = Pet.find(params[:id])
end
# Only allow a trusted parameter "white list" through.
def pet_params
# params.fetch(:pet, {})
params.require(:pet).permit(:user_id, :owner_phone, :owner_address, :species, :name, :weight, :breed, :age_years, :age_months, :sex, :spayed, :housetrained, :housetrained_info, :chipped, :otherdogs, :otherdogs_info, :othercats, :othercats_info, :children, :children_info, :shed, :shed_info, :hypoallergenic, :hypoallergenic_info, :noise, :noise_info, :aggression, :aggression_info, :specialcare, :vet, :about, :instructions)
end
end
|
class AddUserGroupIdToFollowUsers < ActiveRecord::Migration
def self.up
add_column :follow_users, :follows_group_id, :integer
add_column :follow_users, :fans_group_id, :integer
end
def self.down
remove_column :follow_users, :follows_group_id
remove_column :follow_users, :fans_group_id
end
end
|
#
# Cookbook Name:: pgbouncer
# Recipe:: default
# Author:: Christoph Krybus <ckrybus@googlemail.com>
#
# Copyright 2011, Christoph Krybus
#
# 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.
#
package "pgbouncer" do
action :upgrade
end
service "pgbouncer" do
action :nothing
supports :status => true, :start => true, :stop => true, :restart => true, :reload => true
end
template "/etc/pgbouncer/pgbouncer.ini" do
source "pgbouncer.ini.erb"
owner "root"
group "root"
mode "644"
notifies :reload, resources(:service => "pgbouncer")
end
template "/etc/pgbouncer/userlist.txt" do
source "userlist.txt.erb"
owner "root"
group "root"
mode "644"
notifies :reload, resources(:service => "pgbouncer")
end
template "/etc/default/pgbouncer" do
source "pgbouncer.default.erb"
owner "root"
group "root"
mode "644"
notifies :reload, resources(:service => "pgbouncer")
end
service "pgbouncer" do
action [:enable, :start]
end
|
require "builder"
require 'json'
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
# Sitemap
page "/sitemap.xml", layout: false
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
# Global Configuration
# Global Variables
set :global_url, "http://charactercount.io/"
set :global_name, "Character Count"
set :global_domain, "charactercount.io"
set :global_twitter, "@dixonandmoe"
# Pretty URLs
activate :directory_indexes
# Asset paths
set :css_dir, 'assets/stylesheets'
set :js_dir, 'assets/javascripts'
set :images_dir, 'assets/images'
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
# Development Configuration
configure :development do
# Reload the browser automatically whenever files change
activate :livereload
end
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
# Production Configuration
configure :build do
# Enable cache buster
activate :asset_hash
# Minify CSS on build
activate :minify_css
# Minify Javascript on build
activate :minify_javascript
# GZIP files for even better compression
activate :gzip, exts: %w(.js .css .html .htm .xml .txt)
# Ignore DS_Store file
ignore ".DS_Store"
end |
# coding: utf-8
require 'rake'
require 'rake/rdoctask'
begin
require 'spec/rake/spectask'
rescue LoadError
begin
gem 'rspec-rails', '>= 1.0.0'
require 'spec/rake/spectask'
rescue LoadError
puts "RSpec - or one of it's dependencies - is not available. Install it with: sudo gem install rspec-rails"
end
end
NAME = "grimen-delayed_job_mailer"
SUMMARY = %Q{Send emails asynchronously using delayed_job.}
HOMEPAGE = "http://github.com/grimen/#{NAME}"
AUTHOR = "Anderson Dias"
EMAIL = "andersondaraujo@gmail.com"
SUPPORT_FILES = %w(README)
begin
gem 'jeweler', '>= 1.2.1'
require 'jeweler'
Jeweler::Tasks.new do |gemspec|
gemspec.name = NAME
gemspec.summary = SUMMARY
gemspec.description = SUMMARY
gemspec.homepage = HOMEPAGE
gemspec.author = AUTHOR
gemspec.email = EMAIL
gemspec.autorequire = NAME
gemspec.require_paths = %w{lib}
gemspec.files = SUPPORT_FILES << %w(MIT-LICENSE Rakefile) << Dir.glob(File.join(*%w[{lib,spec} ** *]).to_s)
gemspec.extra_rdoc_files = SUPPORT_FILES
gemspec.add_dependency 'actionmailer', '>= 1.2.3'
gemspec.add_dependency 'activesupport', '>= 1.2.3'
gemspec.add_development_dependency 'rspec-rails', '>= 1.2.6'
end
Jeweler::GemcutterTasks.new
rescue LoadError
puts "Jeweler, or one of its dependencies, is not available. Install it with: sudo gem install jeweler -s http://gemcutter.org"
end
desc %Q{Default: Run specs for "#{NAME}".}
task :default => :spec
desc %Q{Generate documentation for "#{NAME}".}
Rake::RDocTask.new(:rdoc) do |rdoc|
rdoc.rdoc_dir = 'rdoc'
rdoc.title = NAME
rdoc.options << '--line-numbers' << '--inline-source' << '--charset=UTF-8'
rdoc.rdoc_files.include(SUPPORT_FILES)
rdoc.rdoc_files.include(File.join(*%w[lib ** *.rb]))
end
SPEC_FILES = Rake::FileList[File.join(*%w[spec ** *_spec.rb])]
if defined?(Spec)
desc %Q{Run specs for "#{NAME}".}
Spec::Rake::SpecTask.new do |t|
t.spec_files = SPEC_FILES
t.spec_opts = ['-c']
end
desc %Q{Generate code coverage for "#{NAME}".}
Spec::Rake::SpecTask.new(:coverage) do |t|
t.spec_files = SPEC_FILES
t.rcov = true
t.rcov_opts = ['--exclude', 'spec,/var/lib/gems']
end
end
|
module Formtastic
module SeparateDateAndTimePickerInput
class Processor
def self.process(attrs)
if attrs
attrs = Hash[attrs.dup]
datetime_attrs = {}
attrs.each do |key, value|
if attr = key[/\A(.*)\((date|time)\)\Z/, 1]
datetime_attrs[attr] ||= {}
datetime_attrs[attr][key] = value
end
end
datetime_attrs.each do |attr, values|
if !values["#{attr}(date)"].blank?
value = (values["#{attr}(date)"] + ' ' + values["#{attr}(time)"]).strip
if !value.blank?
attrs[attr.to_sym] = value
end
end
attrs.delete("#{attr}(date)")
attrs.delete("#{attr}(time)")
end
end
attrs
end
end
end
end
|
class CreatePoliticians < ActiveRecord::Migration[5.0]
def change
create_table :politicians do |t|
t.string :first_name
t.string :last_name
t.string :party
t.string :religion
t.string :prior_experience
t.string :education
t.integer :birth_year
t.string :email
t.integer :state_id
t.timestamps
end
end
end
|
# == Schema Information
#
# Table name: task_orders
#
# id :integer not null, primary key
# game_id :integer
# team_id :integer
# task_id :integer
# order_n :integer
# solved :boolean
# dropped :boolean
# time_start :datetime
# time_hint1 :datetime
# time_hint2 :datetime
# solve_time :datetime
# created_at :datetime not null
# updated_at :datetime not null
#
class TaskOrder < ActiveRecord::Base
attr_accessible :dropped, :game_id, :order_n, :solve_time, :solved, :task_id, :team_id, :time_hint1, :time_hint2, :time_start
belongs_to :team
belongs_to :game
belongs_to :task
acts_as_list :scope => 'team_id=#{team_id} and game_id=#{game_id}', :column => :order_n
validates :task_id, uniqueness: {scope: :team_id }
# validates :task_id, uniqueness: {scope: [ :order_n, :team_id] }
# validates :team_id, uniqueness: {:scope => :order_n}
end
|
require 'spec_helper'
describe "Circle Pages" do
subject { page }
describe "circle page" do
let(:circle) { FactoryGirl.create(:circle) }
before { visit circle_path(circle) }
it { should have_content(circle.name) }
it { should have_title(full_title(circle.name)) }
end
describe "regist circle page" do
before { visit '/circles/new' }
let(:submit) { "Regist" }
describe "with invalid information" do
it "should not regist a circle" do
expect { click_button submit }.not_to change(Circle, :count)
end
end
describe "with valid information" do
before do
fill_in "Name", with: "Example Circle"
end
it "should regist a circle" do
expect { click_button submit }.to change(Circle, :count).by(1)
end
end
end
end
|
module ThoughtLeadr
VERSION = '0.10.0'.freeze unless defined?(::ThoughtLeadr::VERSION)
end |
require 'logger'
class Logger
def debug_var(ctx, *vars)
class_name = ctx.eval("self.class").to_s
if class_name != "Class"
sep = "#"
else
class_name = ctx.eval("self.name")
sep = "."
end
/^(.+?):(\d+)(?::in `(.*)')?/.match(caller.first)
method_name = $3 ? $3 : ""
message_a = vars.map {|var|
"\n" + yellow(var.to_s) + " => " + yellow(ctx.eval(var.to_s).inspect)
}
debug(class_name + sep + method_name) { message_a.join(", ") }
end
end
|
# -*- coding: utf-8 -*-
class ItemsController < ApplicationController
before_filter :set_project_to_variable
def copy
item = find_item_from_params
copy_item = item.dup_deep(@project.org_project_task_id_map)
category_id = params[:category_id]
sub_category_id = params[:sub_category_id]
dst_params = DstItemForm.new(params[:dst_item_form])
copy_item.name = dst_params.name
copy_item.position = nil
if dst_params.valid?
dst_category_id = dst_params.category_id
dst_sub_category_id = dst_params.sub_category_id
if category_id.blank?
@project.categories << copy_item
elsif sub_category_id.blank?
@project.categories.find(dst_category_id).sub_categories << copy_item
else
@project.categories.find(dst_category_id).sub_categories.find(dst_sub_category_id).stories << copy_item
end
@project.save!
render nothing: true, status: :ok
else
render json: dst_params.errors.full_messages, status: :bad_request
end
end
private
def set_project_to_variable
@project = Project.find(params[:project_id])
end
def find_item_from_params
category_id = params[:category_id]
sub_category_id = params[:sub_category_id]
if category_id.blank?
@project.categories.find(params[:id])
elsif sub_category_id.blank?
@project.categories.find(category_id).sub_categories.find(params[:id])
else
@project.categories.find(category_id).sub_categories.find(sub_category_id).stories.find(params[:id])
end
end
end
|
require 'pry'
class MP3Importer
attr_accessor :path
def initialize(path)
@path = path
end
def files
files = Dir.entries(self.path)
files.select{|file| file.match(/.+[mp3]/)}
end
def import
entries = self.files
artist_song = {}
new_artist_song = {}
artist_object = nil
song_object = nil
entries.each {|entry| artist_song[entry[/^([^-]+)\w/]] = entry[/- .+ -/]}
artist_song.each do |artist, song|
song.slice!("- ")
song.slice!(" -")
new_artist_song[artist] = song
end
new_artist_song.each do |artist, song|
artist_object = Artist.new(artist)
song_object = Song.new(song)
artist_object.add_song(song_object)
artist_object.save
end
end
end
|
class AddStudentId < ActiveRecord::Migration[6.0]
def change
add_column :lists, :student_id, :int
end
end
|
require 'csv'
module ActiveModel
class CsvSerializer
@_attributes = []
@associations = []
@root = true
class << self
attr_accessor :_attributes, :associations, :root
end
def self.inherited(base)
base._attributes = []
base.associations = []
base.root = true
end
def self.attributes(*attributes)
@_attributes = @_attributes.concat(attributes)
end
def self.has_one(associated)
@associations << {
associated: associated,
serializer: ActiveModel::CsvSerializerFactory
}
end
def self.has_many(associated)
@associations << {
associated: associated,
serializer: ActiveModel::CsvArraySerializer
}
end
attr_reader :object
def initialize(object, options = {})
@object = object
@root = options.fetch(:root, self.class.root)
@prefix = options.fetch(:prefix, '')
@options = options
end
def to_a
return [[]] unless @object
values = []
values << self.class._attributes.collect { |name| read_attribute(name) }
associated_serializers.each do |serializer|
values = values.product(serializer.to_a).collect(&:flatten)
end
values
end
def to_csv
CSV.generate do |csv|
csv << attribute_names if @root
to_a.each { |record| csv << record }
end
end
def attribute_names
names = self.class._attributes.collect do |attribute|
@prefix + attribute.to_s
end
associated_serializers.reduce(names) do |names, serializer|
names.concat serializer.attribute_names
end.map(&:titleize)
end
private
def read_attribute(name)
return send(name) if respond_to?(name)
object.read_attribute_for_serialization(name)
end
def read_association(name)
respond_to?(name) ? send(name) : object.send(name)
end
def associated_serializers
@associated_serializers ||= self.class.associations.collect do |hash|
object = read_attribute(hash[:associated])
hash[:serializer].new(object, prefix: hash[:associated].to_s + '_')
end
end
end
end
|
module ColorFormulas
# this module uses a system app -iccApplyNamedCmm that must be installed in the PAtH to work
# CONStANtS
RGB_RANGE = 0..255
L_RANGE = 0..100
A_RANGE = -127..127
B_RANGE = -127..127
PATCH_SORT_HASH = {'Paper' => 0, 'Cyan' => 1, 'C70' => 2, 'C30'=> 3, 'Magenta' => 4, 'M70' => 5, 'M30' => 6, 'Yellow' => 7, 'Y70' => 8, 'Y30' => 9, 'Black' => 10, 'K90' => 11, 'K75' => 12, 'K50' => 13, 'K25' => 14, 'K10' => 15, 'K3' => 16, 'Red' => 17, 'Red70' => 18, 'Red30' => 19, 'Green' => 20, 'Green70' => 21, 'Green30' => 22, 'Blue' => 23, 'Blue70' => 24, 'Blue30' => 25, 'Gray75' => 26, 'Gray50' => 27, 'Gray25' => 28, 'Gray10' => 29, 'Gray3' => 30, 'Y100K60' => 31, 'C100Y40' => 32, 'C40M100' => 33, 'M40Y100' => 34, 'M40Y70K40' => 35, 'M70Y40K40' => 36, 'C40M70K40' => 37, 'C40Y70K40' => 38, 'C70M40K40' => 39, 'C100M100K60' => 40, 'M100Y100K60' => 41, 'C100Y100K60' => 42, 'C100M40' => 43, 'M100Y40' => 44, 'C40Y100' => 45, 'C10M40Y40' => 46, 'C20M70Y70' => 47, 'M70Y70K40' => 48, 'C70Y40K40' => 49, 'C100M100Y100' => 50, 'C80M70Y70K100' => 51, 'C100K60' => 52, 'M100K60 ' => 53 }
def lab_to_rgb(l,a,b)
# logger.error("************\nHERE\n#{self.id}\n************")
if validate_lab?(l,a,b) then
lab_file_content = "'Lab ' ; Data Format\nicEncodeValue ; Encoding\n"
lab_file_content += "#{l} #{a} #{b}"
# create random temp file name
lab_file_path = "#{Rails.root}/tmp/#{(0...8).map{65.+(rand(25)).chr}.join}.txt"
icc_profile_path = "#{Rails.root}/vendor/AdobeRgB1998.icc"
lab_file = File.new(lab_file_path, 'w')
lab_file.puts lab_file_content
lab_file.close
begin
# trap for iccApplyNamedCmm not being installed
raise "iccApplyNamedCmm not found in PAtH: #{`echo $PAtH`}" if "" == `which iccApplyNamedCmm`
iccSystemCallValue = `iccApplyNamedCmm #{lab_file_path} 3 1 #{icc_profile_path} 1`.split(/;/)
/(\d+)\.\d+\s+(\d+)\.\d+\s+(\d+)\.\d+/.match(iccSystemCallValue[-2])
r, g, b = $1, $2, $3
rescue RuntimeError => system_path_error
r, g, b = 0, 0, 0
logger.error("\n[ColorFormulas.lab_to_rgb::iccApplyNamedCmm] #{system_path_error}\n")
ensure
File.delete(lab_file_path)
end
# ensure ALL values are 0..255
if validate_rgb?(r, g, b)
return [r, g, b]
else
# unless all colors are valid return BLACK
logger.error("\n[ColorFormulas.validate_rgb] ERROR with #{self.inspect}\n")
return [0,0,0]
end
else
logger.error("\n[ColorFormulas.validate_lab] ERROR with #{self.inspect}")
[0,0,0]
end
end
def to_hex(int)
if int.to_s(16)
# put 0 in front of the hex char to insure a two digit hex char
/.*([A-z0-9]{2})$/.match("0#{int.to_s(16)}")
return $1
else
logger.error("[ColorFormulas.to_hex] ERROR converting #{int.inspect} into a hex")
"00"
end
end
def lab_dE2000(l1, a1, b1, l2, a2, b2)
kl = 1
kc = 1
kh =1
# FROM SetLabData -- NOt SURE IF NEEDED, but I think so
c1 = Math::sqrt(a1 ** 2 + b1 ** 2)
c2 = Math::sqrt(a2 ** 2 + b2 ** 2)
h1 = Math::atan2(a1,b1) * (180 / Math::PI)
if h1 < 0
h1 = h1 + 360
end
h2 = Math::atan2(a2,b2) * (180 / Math::PI)
if h2 < 0
h2 = h2 + 360
end
# FROM dE2000
lPrimeMean = (l1 + l2) / 2
cMean = (c1 + c2) / 2
g = (1 - Math::sqrt(cMean ** 7 / (cMean ** 7 + 25 ** 7))) / 2
a1prime = a1 * (1 + g)
a2prime = a2 * (1 + g)
c1prime = Math::sqrt(a1prime ** 2 + b1 ** 2)
c2prime = Math::sqrt(a2prime ** 2 + b2 ** 2)
cPrimeMean = (c1prime + c2prime) / 2
if Math::atan2(a1prime, b1) * (180 / Math::PI) >= 0
h1prime = Math::atan2(a1prime, b1) * (180 / Math::PI)
else
h1prime = Math::atan2(a1prime, b1) * (180 / Math::PI) + 360
end
if Math::atan2(a2prime, b2) * (180 / Math::PI) >= 0
h2prime = Math::atan2(a2prime, b2) * (180 / Math::PI)
else
h2prime = Math::atan2(a2prime, b2) * (180 / Math::PI) + 360
end
if (h1prime - h2prime).abs > 180
hPrimeMean = (h1prime + h2prime + 360) / 2
else
hPrimeMean = (h1prime + h2prime) / 2
end
t = 1 - 0.17 * Math::cos((hPrimeMean - 30) * (Math::PI / 180)) + 0.24 * Math::cos(2 * hPrimeMean * (Math::PI / 180)) + 0.32 * Math::cos((3 * hPrimeMean + 6) * (Math::PI / 180)) - 0.2 * Math::cos((4 * hPrimeMean - 63) * (Math::PI / 180))
if (h2prime - h1prime).abs <= 180
dsHprime = h2prime - h1prime
else
if h2prime <= h1prime
dsHprime = h2prime - h1prime + 360
else
dsHprime = h2prime - h1prime - 360
end
end
dLprime = l2 - l1
dCprime = c2prime - c1prime
dHprime2 = 2 * Math::sqrt(c1prime * c2prime) * Math::sin(dsHprime / 2 * (Math::PI / 180))
sl = (0.015 * (lPrimeMean - 50) ** 2) / Math::sqrt(20 + (lPrimeMean - 50) ** 2) + 1
sc = 1 + 0.045 * cPrimeMean
sh = 1 + 0.015 * cPrimeMean * t
dtheta = 30 * Math::exp(-1 * (((hPrimeMean - 275) / 25) ** 2))
rc = Math::sqrt(cPrimeMean ** 7 / (cPrimeMean ** 7 + 25 ** 7))
rt = -2 * rc * Math::sin(2 * dtheta * Math::PI / 180)
deltaE2000 = Math::sqrt((dLprime / (kl * sl)) ** 2 + (dCprime / (kc * sc)) ** 2 + (dHprime2 / (kh * sh)) ** 2 + rt * (dCprime / (kc * sc)) * (dHprime2 / (kh * sh)))
format("%.2f", deltaE2000).to_f
end
private
def validate_lab?(l,a,b)
return false unless l && L_RANGE.include?(l.to_f)
return false unless a && A_RANGE.include?(a.to_f)
return false unless b && B_RANGE.include?(b.to_f)
# if all these pass then it is ok
true
end
def validate_rgb?(r, g, b)
return false unless r.to_i && RGB_RANGE.include?(r.to_i)
return false unless g.to_i && RGB_RANGE.include?(g.to_i)
return false unless b.to_i && RGB_RANGE.include?(b.to_i)
# if all these pass then it is ok
true
end
end
|
# frozen_string_literal: true
require 'rails_helper'
RSpec.describe User do
let(:blank_photo) { 'https://static.bpsd9.org/no_profile.png' }
let(:user) { create(:user) }
context 'with a new user' do
let(:user) { build(:user) }
it 'defaults to the blank profile photo' do
expect(user.photo).to eql(blank_photo)
end
end
describe 'validations' do
it 'rejects invalid ranks' do
user = build(:user, rank: 'D/F/Lt/C')
expect(user).not_to be_valid
end
it 'accepts valid ranks' do
user = build(:user, rank: 'D/F/Lt')
expect(user).to be_valid
end
it 'rejects invalid grades' do
user = build(:user, grade: 'SP')
expect(user).not_to be_valid
end
it 'accepts valid grades' do
user = build(:user, grade: 'JN')
expect(user).to be_valid
end
it 'replaces blank ranks with nil' do
user = build(:user, rank: ' ')
user.validate
expect(user.rank).to be_nil
end
it 'rejects invalid phone_c' do
user = build(:user, phone_c: 'not-a-number')
user.validate
expect(user).not_to be_valid
end
end
context 'with specified user' do
let(:user) { create(:user, first_name: 'John', last_name: 'Doe', rank: 'Lt/C', grade: 'AP') }
describe 'auto_rank' do
it 'correctlies detect Cdr' do
assign_bridge_office('commander', user)
expect(user.auto_rank).to eql('Cdr')
end
it 'correctlies detect Lt/C' do
assign_bridge_office('executive', user)
expect(user.auto_rank).to eql('Lt/C')
end
it 'correctlies detect 1st/Lt' do
user.rank = nil
assign_bridge_office('asst_secretary', user)
expect(user.auto_rank(html: false)).to eql('1st/Lt')
end
it 'returns the correct string for a formatted rank' do
user.rank = nil
assign_bridge_office('asst_educational', user)
expect(user.auto_rank).to eql('1<sup>st</sup>/Lt')
end
it 'returns the correct string for a simple rank' do
expect(user.auto_rank).to eql('Lt/C')
end
end
describe '#stripe_rank' do
it 'returns the correct rank, properly formatted' do
allow(user).to receive(:ranks).and_return(['R/C', 'Lt/C', 'D/Lt'])
expect(user.stripe_rank).to eq('rc')
end
it 'includes GB Emeritus' do
allow(user).to receive(:ranks).and_return(['Lt/C', 'D/Lt'])
allow(user).to receive(:mm).and_return(50)
expect(user.stripe_rank).to eq('stfc')
end
describe 'regexes' do
let(:narrow) { User::Stripes::NARROW }
let(:two) { User::Stripes::TWO }
let(:three) { User::Stripes::THREE }
let(:four) { User::Stripes::FOUR }
let(:levels) { %i[NATIONAL DISTRICT SQUADRON].map { |l| User::Stripes.const_get(l) } }
shared_examples 'has four stripes with' do |level|
it('has the correct main stripe') { expect(rank).to match(level) }
it('has a second stripe') { expect(rank).to match(two) }
it('has a third stripe') { expect(rank).to match(three) }
it('has a fourth stripe') { expect(rank).to match(four) }
it 'does not have the incorrect stripes', :aggregate_failures do
(levels - [level]).each { |l| expect(rank).not_to match(l) }
end
end
shared_examples 'has three stripes with' do |level|
it('has the correct main stripe') { expect(rank).to match(level) }
it('has a second stripe') { expect(rank).to match(two) }
it('has a third stripe') { expect(rank).to match(three) }
it('does not have a fourth stripe') { expect(rank).not_to match(four) }
it 'does not have the incorrect stripes', :aggregate_failures do
(levels - [level]).each { |l| expect(rank).not_to match(l) }
end
end
shared_examples 'has two stripes with' do |level|
it('has the correct main stripe') { expect(rank).to match(level) }
it('has a second stripe') { expect(rank).to match(two) }
it('does not have a third stripe') { expect(rank).not_to match(three) }
it('does not have a fourth stripe') { expect(rank).not_to match(four) }
it 'does not have the incorrect stripes', :aggregate_failures do
(levels - [level]).each { |l| expect(rank).not_to match(l) }
end
end
shared_examples 'has one stripe with' do |level|
it('has the correct main stripe') { expect(rank).to match(level) }
it('does not have a second stripe') { expect(rank).not_to match(two) }
it('does not have a third stripe') { expect(rank).not_to match(three) }
it('does not have a fourth stripe') { expect(rank).not_to match(four) }
it 'does not have the incorrect stripes', :aggregate_failures do
(levels - [level]).each { |l| expect(rank).not_to match(l) }
end
end
describe 'no rank' do
let(:rank) { nil }
it('does not have a second stripe') { expect(rank).not_to match(two) }
it('does not have a third stripe') { expect(rank).not_to match(three) }
it('does not have a fourth stripe') { expect(rank).not_to match(four) }
it 'does not have a main stripe', :aggregate_failures do
levels.each { |l| expect(rank).not_to match(l) }
end
end
describe 'national' do
context 'with cc' do
%w[cc pcc].each do |r|
let(:rank) { r }
include_examples 'has four stripes with', User::Stripes::NATIONAL
it('is narrow-spaced') { expect(rank).to match(narrow) }
end
end
context 'with vc' do
%w[vc pvc].each do |r|
let(:rank) { r }
include_examples 'has three stripes with', User::Stripes::NATIONAL
end
end
context 'with rc' do
%w[rc prc].each do |r|
let(:rank) { r }
include_examples 'has two stripes with', User::Stripes::NATIONAL
end
end
context 'with other national' do
%w[stfc pstfc nflt pnflt naide].each do |r|
let(:rank) { r }
include_examples 'has one stripe with', User::Stripes::NATIONAL
end
end
end
describe 'district' do
context 'with dc' do
%w[dc pdc].each do |r|
let(:rank) { r }
include_examples 'has four stripes with', User::Stripes::DISTRICT
it('is narrow-spaced') { expect(rank).to match(narrow) }
end
end
context 'with dltc' do
%w[dltc pdltc].each do |r|
let(:rank) { r }
include_examples 'has three stripes with', User::Stripes::DISTRICT
end
end
context 'with d1lt' do
%w[dfirstlt].each do |r|
let(:rank) { r }
include_examples 'has two stripes with', User::Stripes::DISTRICT
end
end
context 'with other district' do
%w[dlt dflt daide].each do |r|
let(:rank) { r }
include_examples 'has one stripe with', User::Stripes::DISTRICT
end
end
end
describe 'squadron' do
context 'with cdr' do
%w[cdr pc].each do |r|
let(:rank) { r }
include_examples 'has four stripes with', User::Stripes::SQUADRON
it('is not narrow-spaced') { expect(rank).not_to match(narrow) }
end
end
context 'with ltc' do
%w[ltc pltc].each do |r|
let(:rank) { r }
include_examples 'has three stripes with', User::Stripes::SQUADRON
end
end
context 'with 1lt' do
%w[firstlt].each do |r|
let(:rank) { r }
include_examples 'has two stripes with', User::Stripes::SQUADRON
end
end
context 'with other squadron' do
%w[lt flt].each do |r|
let(:rank) { r }
include_examples 'has one stripe with', User::Stripes::SQUADRON
end
end
end
end
end
describe '#first_stripe_class' do
subject(:first_stripe_class) { user.first_stripe_class }
it 'matches national' do
allow(user).to receive(:stripe_rank).and_return('rc')
expect(first_stripe_class).to eq(:national)
end
it 'matches district' do
allow(user).to receive(:stripe_rank).and_return('dltc')
expect(first_stripe_class).to eq(:district)
end
it 'matches squadron' do
allow(user).to receive(:stripe_rank).and_return('flt')
expect(first_stripe_class).to eq(:squadron)
end
it 'detects nothing' do
allow(user).to receive(:stripe_rank).and_return(nil)
expect(first_stripe_class).to eq(:hide)
end
end
describe 'formatting' do
it 'has the correct simple_name' do
expect(user.simple_name).to eql('John Doe')
end
it 'has the correct full_name' do
expect(user.full_name).to eql('Lt/C John Doe, AP')
end
describe 'BOC' do
it 'returns nil for no BOC level' do
expect(create(:user).boc).to be_nil
end
describe 'with BOC level' do
let(:user) { create(:user) }
let!(:completion) { create(:course_completion, user: user, course_key: 'BOC_IN') }
it 'returns the correct BOC level' do
expect(user.boc).to eql('IN')
end
describe 'with endorsements' do
before do
create(:course_completion, user: user, course_key: 'BOC_CAN')
end
it 'returns the correct BOC level with endorsements' do
expect(user.boc).to eql('IN (CAN)')
end
it 'generates the correct grade suffix' do
expect(user.boc_display).to eql('-IN')
end
end
end
end
it 'returns the correct bridge_hash' do
expect(user.bridge_hash).to eql(
full_name: 'Lt/C John Doe, AP',
simple_name: 'John Doe',
photo: blank_photo
)
end
end
end
describe 'inviting' do
let(:user) { create(:user) }
let(:placeholder_user) { create(:user, :placeholder_email) }
it 'is invitable by default' do
expect(user.invitable?).to be(true)
end
it 'does not have accepted an invitation' do
user.update(invitation_accepted_at: Time.zone.now)
expect(user.invitable?).to be(false)
end
it 'is not logged in' do
user.update(current_sign_in_at: Time.zone.now)
expect(user.invitable?).to be(false)
end
it 'is not locked' do
user.lock
expect(user.invitable?).to be(false)
end
it 'does not have a sign in count' do
user.update(sign_in_count: 1)
expect(user.invitable?).to be(false)
end
it 'does not have a placeholder email' do
expect(placeholder_user.invitable?).to be(false)
end
it 'has received but not accepted an invitation' do
user.update(invitation_sent_at: Time.zone.now)
expect(user.invited?).to be(true)
end
describe '.invitable_from' do
subject { described_class.invitable_from(user.id, already_invited.id) }
let(:already_invited) { create(:user, invitation_sent_at: Time.zone.now) }
it { is_expected.to eq([user]) }
end
end
describe 'registration' do
let(:event) { create(:event) }
let(:user) { create(:user) }
before { assign_bridge_office('educational', user) }
it 'creates a valid registration' do
reg = user.register_for(event)
expect(reg).to be_valid
end
it 'finds an existing registration' do
existing = user.register_for(event)
reg = user.register_for(event)
expect(reg).to eq(existing)
end
it 'creates a valid registration with an existing refunded registration' do
original = user.register_for(event)
original.payment.update(refunded: true)
reg = user.register_for(event)
expect(reg).to be_valid
end
end
describe 'permissions' do
let!(:admin) { create(:role, name: 'admin') }
let!(:child) { create(:role, name: 'child', parent: admin) }
let(:user) { create(:user) }
it 'adds permissions correctly' do
user_role = user.permit! :child
expect(user_role.user).to eq(user)
expect(user_role.role).to eq(child)
end
describe 'removal' do
before do
user.permit! :admin
user.permit! :child
end
it 'removes permissions correctly' do
user.unpermit! :child
expect(user.permitted_roles).to include(:admin)
end
it 'removes all permissions correctly' do
user.unpermit! :all
expect(user.permitted_roles).to be_blank
end
end
it 'returns true when user has the required permission' do
user.permit! :child
expect(user.reload).to be_permitted(:child)
end
it 'returns true when user has a parent of the required permission' do
user.permit! :admin
expect(user.reload).to be_permitted(:child)
end
it 'returns false when user does not have the required permission' do
expect(user.reload).not_to be_permitted(:child)
end
it "returns false when a role doesn't exist" do
expect(user).not_to be_permitted(:not_a_permission)
end
it 'returns false for invalid/empty permissions', :aggregate_failures do
expect(user).not_to be_permitted(nil)
expect(user).not_to be_permitted([])
expect(user).not_to be_permitted({})
expect(user).not_to be_permitted('')
expect(user).not_to be_permitted(' ')
expect(user).not_to be_permitted(nil, [], {}, '', ' ')
end
it 'returns the correct lists of permissions' do
user.permit! :admin
expect(user.granted_roles).to eq([:admin])
expect(user.permitted_roles).to eq(%i[admin child])
expect(user.implied_roles).to eq(%i[child])
end
describe 'show_admin_menu?' do
let!(:page) { create(:role, name: 'page') }
it 'shows the admin menu for correct users' do
user.permit! :page
expect(user).to be_show_admin_menu
end
it 'does not show the admin menu for other users' do
expect(user).not_to be_show_admin_menu
end
end
describe 'authorized_for_activity_feed?' do
let!(:education) { create(:role, name: 'education') }
let!(:event) { create(:role, name: 'event') }
it 'does not allow a regular user to edit' do
expect(user).not_to be_authorized_for_activity_feed
end
it 'allows an admin to edit' do
user.permit! :admin
expect(user).to be_authorized_for_activity_feed
end
context 'with education permissions' do
it 'allows granted education permissions to edit' do
user.permit! :education
expect(user).to be_authorized_for_activity_feed
end
it 'allows implied education permissions to edit' do
create(:bridge_office, office: 'asst_educational', user: user)
expect(user).to be_authorized_for_activity_feed
end
end
end
describe 'role checkers' do
let!(:education) { create(:role, name: 'education') }
describe '#role?' do
it 'is true when directly granted' do
user.permit! :education
expect(user).to be_role(:education)
end
it 'is true when implied' do
user.permit! :admin
expect(user).to be_role(:education)
end
it 'is false when not permitted' do
expect(user).not_to be_role(:education)
end
end
describe '#exact_role?' do
it 'is true when directly granted' do
user.permit! :education
expect(user).to be_exact_role(:education)
end
it 'is false when implied' do
user.permit! :admin
expect(user).not_to be_exact_role(:education)
end
end
end
end
describe 'locking' do
let(:user) { create(:user) }
it 'does not create locked users' do
expect(user.locked?).to be(false)
end
it 'correctly lock users' do
expect { user.lock }.to change { user.locked? }.to(true)
end
it 'correctly unlock users' do
user.lock
expect { user.unlock }.to change { user.locked? }.to(false)
end
end
describe 'scopes' do
let!(:user_inv) { create(:user) }
let!(:user_pe) { create(:user, email: 'nobody-asdfhjkl@bpsd9.org') }
let!(:user_inst) { create(:user, sign_in_count: 1, id_expr: 1.year.from_now) }
let!(:user_vse) { create(:user, sign_in_count: 23) }
before do
user_vse.course_completions << create(
:course_completion, user: user_vse, course_key: 'VSC_01', date: 1.month.ago
)
end
it 'returns the list of invitable users' do
expect(described_class.invitable.to_a).to eql([user_inv])
end
it 'returns the list of valid instructor users' do
expect(described_class.valid_instructors.to_a).to eql([user_inst])
end
it 'returns the list of vessel examiner users' do
expect(described_class.vessel_examiners.to_a).to eql([user_vse])
end
end
describe 'address' do
let(:user) { create(:user, address_1: '100 N Capitol Ave', city: 'Lansing', state: 'MI', zip: '48933') }
it 'returns a correct address array' do
expect(user.mailing_address).to eql([user.full_name, user.address_1, "#{user.city} #{user.state} #{user.zip}"])
end
it 'returns valid Lat Lon' do
expect(user.lat_lon(human: false).join("\t")).to match(/-?\d{1,3}\.\d+\t-?\d{1,3}\.\d+/)
end
it 'returns valid human-readable Lat Lon' do
expect(user.lat_lon(human: true)).to match(/\d{1,3}° \d{1,2}\.\d{1,5}′ [NS]\t\d{1,3}° \d{1,2}\.\d{1,5}′ [EW]/)
end
end
describe 'profile photo' do
let(:user) { create(:user) }
let(:photo) { File.new(test_image(500, 750)) }
it 'returns the default photo if not present' do
expect(user.photo).to eql(described_class.no_photo)
end
it 'requires a file path' do
expect { user.assign_photo }.to raise_error(ArgumentError, 'missing keyword: :local_path')
expect { user.assign_photo(local_path: photo.path) }.not_to raise_error
end
it 'has a photo after attaching' do
user.assign_photo(local_path: photo.path)
expect(user.photo).to match(
%r{https://files\.development\.bpsd9\.org/profile_photos/#{user.id}/medium/test_image\.jpg\?}
)
end
end
describe 'dues' do
it 'returns the correct single member amount' do
expect(user.dues).to be(89)
end
it 'returns the correct discounted amount' do
expect(user.discounted_amount).to eq(86.75)
end
context 'with family' do
let!(:child) { create(:user, parent: user) }
it 'returns the correct family amount' do
expect(user.dues).to eq(134)
end
it 'returns the parent_id hash if a parent is assigned' do
expect(child.dues).to eql(user_id: user.id)
end
describe 'payable?' do
it 'returns true for a parent' do
expect(user.payable?).to be(true)
end
it 'returns false for a child' do
expect(child.payable?).to be(false)
end
it 'returns true for a recently-paid member' do
user.dues_paid!
expect(user.payable?).to be(true)
end
end
end
end
describe 'dues_due' do
let(:child) { create(:user, parent: user) }
it 'returns false with if not the head of a family' do
expect(child.dues_due?).to be(false)
end
it 'returns false with dues paid within 11 months' do
user.update(dues_last_paid_at: 3.months.ago)
expect(user.dues_due?).to be(false)
end
it 'returns true with dues paid over 11 months ago' do
user.update(dues_last_paid_at: 11.months.ago)
expect(user.dues_due?).to be(true)
end
end
describe 'valid_instructor?' do
it 'returns false for a nil id_expr' do
expect(user.valid_instructor?).to be(false)
end
it 'returns false for a past id_expr' do
user.update(id_expr: 1.month.ago)
expect(user.valid_instructor?).to be(false)
end
it 'returns true for a future id_expr' do
user.update(id_expr: 1.month.from_now)
expect(user.valid_instructor?).to be(true)
end
end
describe 'vessel_examiner?' do
it 'returns false without VSC training' do
expect(user.vessel_examiner?).to be(false)
end
it 'returns true with VSC training' do
create(:course_completion, user: user, course_key: 'VSC_01', date: Time.zone.today)
expect(user.vessel_examiner?).to be(true)
end
end
describe 'cpr_aed?' do
it 'returns false without the flag set' do
expect(user.cpr_aed?).to be(false)
end
it 'returns false with a past expiration date' do
user.update(cpr_aed_expires_at: 1.day.ago)
expect(user.cpr_aed?).to be(false)
end
it 'returns true with a future expiration date' do
user.update(cpr_aed_expires_at: 1.day.from_now)
expect(user.cpr_aed?).to be(true)
end
end
it 'returns the correct associations to include' do
expect(described_class.position_associations).to eql(
%i[bridge_office standing_committee_offices committees user_roles roles]
)
end
describe 'api access' do
let(:token) { user.create_token }
describe '#token_exists?' do
it 'exists when valid' do
expect(user).to be_token_exists(token.new_token)
end
it 'does not exist when invalid' do
expect(user).not_to be_token_exists('invalid')
end
it 'also finds persistent tokens' do
token
persistent = user.create_token(persistent: true)
expect(user).to be_token_exists(persistent.new_token)
end
end
describe '#token_expired?' do
it 'is expired' do
t = token.new_token
token.update(expires_at: 5.minutes.ago)
expect(user).to be_token_expired(t)
end
it 'is not expired when current' do
expect(user).not_to be_token_expired(token.new_token)
end
end
describe '#create_token' do
it 'creates a new token' do
expect { token }.to change { ApiToken.count }.by(1)
end
it 'has the new token accessible' do
expect(token.new_token).not_to be_nil
end
it 'does not expose stored tokens' do
expect(ApiToken.find(token.id).new_token).to be_nil
end
it 'creates persistent tokens' do
expect(user.create_token(persistent: true).expires_at).to be_nil
end
end
describe '#any_current_tokens?' do
it 'detects temporary tokens' do
token
expect(user).to be_any_current_tokens
end
it 'detects persistent tokens' do
user.create_token(persistent: true)
expect(user).to be_any_current_tokens
end
end
describe 'token associations' do
let!(:at) { ApiToken.create(user: user) }
let!(:pat) { PersistentApiToken.create(user: user) }
it 'includes only expiring tokens' do
expect(user.api_tokens.current).to contain_exactly(at)
end
it 'includes only persistent tokens' do
expect(user.persistent_api_tokens.current).to contain_exactly(pat)
end
end
end
end
|
class CommentsController < ApplicationController
def index
comments = Comment.all.order({ :created_at => :asc })
render({ :json => comments.as_json })
end
def show
the_id = params.fetch(:the_comment_id)
comment = Comment.where({ :id => the_id }).at(0)
render({ :json => comment.as_json })
end
def create
comment = Comment.new
comment.author_id = session.fetch(:user_id)
comment.photo_id = params.fetch(:input_photo_id, nil)
comment.body = params.fetch(:input_body, nil)
comment.save
respond_to do |format|
format.json do
render({ :json => comment.as_json })
end
format.html do
redirect_to("/photos/#{comment.photo_id}")
end
end
end
def update
the_id = params.fetch(:the_comment_id)
comment = Comment.where({ :id => the_id }).at(0)
comment.author_id = params.fetch(:input_author_id, comment.author_id)
comment.photo_id = params.fetch(:input_photo_id, comment.photo_id)
comment.body = params.fetch(:input_body, comment.body)
comment.save
render({ :json => comment.as_json })
end
def destroy
the_id = params.fetch(:the_comment_id)
comment = Comment.where({ :id => the_id }).at(0)
comment.destroy
render({ :json => comment.as_json })
end
end
|
class PhotosDAO
def self.create_photo( photo_h, relation )
if relation == "User"
user_id = photo_h.delete( :user_id )
elsif relation == "Product"
product_id = photo_h.delete( :product_id )
end
photo = Photo.create( photo_h )
if relation == "User"
user = User.load_user_by_id( user_id )
user.photo = photo
user.save
elsif relation == "Product"
product = Product.load_product_by_id( product_id )
product.photos << photo
product.save
end
return photo
end
def self.update_photo( photo_h )
if relation == "User"
user_id = photo_h.delete( :user_id )
elsif relation == "Product"
product_id = photo_h.delete( :product_id )
end
photo = Photo.load_photo_by_id( photo_h.delete( :id ) )
photo.update( photo_h )
=begin if relation == "User"
user = User.load_user_by_id( user_id )
user.photo = photo
user.save
elsif relation == "Product"
product = Product.load_product_by_id( product_id )
product.photos << photo
product.save
end
=end
return photo
end
def self.delete_photo( id )
photo = Photo.load_photo_by_id( id )
if photo == nil
return false
end
photo.destroy
return true
end
def self.delete_photos( ids )
ids.each do |id|
self.delete_photo( id )
end
end
end
|
class PagesController < ApplicationController
def front
redirect_to home_path if user_signed_in?
end
end |
class MyHashSet # Clone Set class
attr_accessor :store
def initialize
@store = Hash.new { |h, k| h[k] = false }
end
def insert(element)
@store[element] = true
end
def include?(element)
store[element]
end
def delete(element)
if store[element]
@store[element] = false
true
else
false
end
end
def to_a
key_array = []
store.each do |key, value|
key_array << key if value
end
key_array
end
def union(other_set)
new_set = MyHashSet.new
(self.to_a + other_set.to_a ).each do |key|
new_set.insert(key)
end
new_set
end
def intersect(other_set)
new_set = MyHashSet.new
self.to_a.select { |key| other_set.to_a.include? key }.each do |key|
new_set.insert(key)
end
new_set
end
def minus(other_set)
new_set = MyHashSet.new
(self.to_a - other_set.to_a).each do |key|
new_set.insert(key)
end
new_set
end
end
|
class Player
attr_reader :name
attr_accessor :stack, :playing, :hand, :bet, :called, :acted
def initialize(name, stack)
@name = name
@stack = stack
@hand = Hand.new
@called = 0 # what player has committed
@playing = false
@acted = false
end
def fold
@playing = false
@stack -= @called
@hand = Hand.new
end
def call(amount)
@called += amount
end
def check
bet_raise(0, 0)
end
def bet_raise(call_amt, amount)
call(call_amt)
@called += amount
end
#
# def all_in
# bet_raise(@stack - @bet)
# end
def discard(indices)
indices.each { |i| @hand.cards.delete_at(i) }
end
end
|
class Product < ActiveRecord::Base
include Filterable
has_many :images
has_many :order_items
belongs_to :product_category
validates :name, presence: true, uniqueness: true
validates :descr, presence: true
validates :product_category, presence: true
default_scope {
where(available: true)
}
def self.search(query)
where "descr ilike ? or name ilike ?", "%#{query}%", "%#{query}%"
end
def self.category(query)
if query=="plant"
where "product_category_id = 1"
elsif query=="bonsay"
where "product_category_id = 2"
elsif query=="flower"
where "product_category_id = 3"
else
where "1=1"
end
end
def self.amount(query)
a=query.index("-")
b=query[1..a-1]
c=query[a..query.size]
c=c[c.index("$")+1..c.size]
if query.index("$")==0
where "price > ? and price < ?", b, c
else
where "1=1"
end
end
end
|
class Chapter < ApplicationRecord
extend FriendlyId
friendly_id :title, use: [:slugged, :finders]
belongs_to :book
acts_as_taggable_on :chapter_tags
validates :title, :contents, presence: true
end
|
module Exceptions
class UnhandledException < StandardError
end
class WorkerFailedJobNotfound < StandardError
end
class JobFailedParamError < StandardError
end
class JobFailedStepRaised < StandardError
end
class JobFailedStepRun < StandardError
end
end |
class ApplicationRecord < ActiveRecord::Base
self.abstract_class = true
def self.per(per_page)
per_page ||= 20
offset = @page * per_page
return [] if @page != 0 && (count / offset) < 1
return all if per_page >= count
limit(per_page).offset(offset)
end
def self.page(page)
@page = (page.to_i - 1)
self
end
end
|
class Location
include Mongoid::Document
include Mongoid::Timestamps
field :restaurant, type:String
field :style, type:String
field :upvotes, type:Array
field :downvotes, type:Array
field :suggester_id, type:String
embedded_in :lunch
end
|
class MockPresenter
attr_accessor :recorded_errors
@display_errors_called = false
@display_success_called = false
@display_logs_called = false
@recorded_errors = []
def display_errors(errors)
@display_errors_called = true
self.recorded_errors = errors
end
def display_success(message)
@display_success_called = true
end
def display_log(log)
@display_logs_called = true
end
def display_errors_called?
@display_errors_called
end
def display_success_called?
@display_success_called
end
end
|
class Clients
attr_accessor :name, :children, :age, :num_pets, :pet_name
def initialize(name, children, age, num_pets)
@name = name
@children = children
@age = age
@num_pets = num_pets
@pet_name = []
end
def to_s
puts "The client is #{@name}, has #{@children} kids, is #{@age} years old and has #{@num_pets} pets.#{@pet_name}"
end
end
|
class AddingShowInReportToDescriptiveIndicator < ActiveRecord::Migration
def self.up
add_column :descriptive_indicators,:show_in_report,:boolean,:default=>false
end
def self.down
remove_column :descriptive_indicators,:show_in_report,:boolean
end
end
|
class AddTotalCaloresToSandwiches < ActiveRecord::Migration[5.0]
def change
add_column :sandwiches, :total_calores, :integer, :default => 0
end
end
|
describe Advisor::Factory do
subject(:factory) { described_class.new(advice_klass) }
let(:advice_klass) do
Struct.new(:obj, :method, :call_args, :args) do
define_method(:call) { 'overridden!' }
define_singleton_method(:applier_method) { 'apply_advice_to' }
end
end
let(:advice_instance) do
advice_klass.new(advised_instance, :apply_advice_to, [], arg1: 1, arg2: 2)
end
let(:advised_klass) do
advisor = build
Struct.new(:advised_method) do
extend advisor
apply_advice_to :advised_method, arg1: 1, arg2: 2
end
end
let(:advised_instance) { advised_klass.new(33) }
before do
allow(advised_klass).to receive(:new)
.and_return(advised_instance)
allow(advice_klass).to receive(:new)
.and_return(advice_instance)
end
describe '#build' do
subject(:build) { factory.build }
it { is_expected.to be_kind_of(Module) }
describe 'when applying the advice to methods' do
subject(:invoke_advised_method) { advised_instance.advised_method }
it do
expect(advice_klass).to receive(:new)
.with(advised_instance, :advised_method, [], arg1: 1, arg2: 2)
invoke_advised_method
end
it do
expect(advice_instance).to receive(:call)
invoke_advised_method
end
it { is_expected.to eq('overridden!') }
end
end
end
|
# frozen_string_literal: true
require 'application_system_test_case'
class HouseholdsTest < ApplicationSystemTestCase
setup do
@household = households(:one)
end
test 'visiting the index' do
visit households_url
assert_selector 'h1', text: 'Households'
end
test 'creating a Household' do
visit households_url
click_on 'New Household'
fill_in 'Uin', with: @household.UIN
fill_in 'Classification', with: @household.classification
fill_in 'Email', with: @household.email
fill_in 'Family', with: @household.family
fill_in 'First', with: @household.first
fill_in 'Last', with: @household.last
fill_in 'Major', with: @household.major
fill_in 'Phonenumber', with: @household.phonenumber
click_on 'Create Household'
assert_text 'Household was successfully created'
click_on 'Back'
end
test 'updating a Household' do
visit households_url
click_on 'Edit', match: :first
fill_in 'Uin', with: @household.UIN
fill_in 'Classification', with: @household.classification
fill_in 'Email', with: @household.email
fill_in 'Family', with: @household.family
fill_in 'First', with: @household.first
fill_in 'Last', with: @household.last
fill_in 'Major', with: @household.major
fill_in 'Phonenumber', with: @household.phonenumber
click_on 'Update Household'
assert_text 'Household was successfully updated'
click_on 'Back'
end
test 'destroying a Household' do
visit households_url
page.accept_confirm do
click_on 'Destroy', match: :first
end
assert_text 'Household was successfully destroyed'
end
end
|
require 'set'
module Racc
# Helper to implement set-building algorithms, whereby each member which is
# added to a set may result in still others being added, until the entire
# set is found
# Each member of the set (and the initial `worklist` if an explicit one is
# given) will be yielded once; the block should either return `nil`, or an
# `Enumerable` of more members
def self.set_closure(seed, worklist = seed)
worklist = worklist.is_a?(Array) ? worklist.dup : worklist.to_a
result = Set.new(seed)
until worklist.empty?
if found = yield(worklist.shift, result)
found.each do |member|
worklist.push(member) if result.add?(member)
end
end
end
result
end
def self.to_sentence(words, conjunction = 'and')
raise "Can't make a sentence out of zero words" if words.none?
if words.one?
words[0]
elsif words.size == 2
"#{words[0]} #{conjunction} #{words[1]}"
else
tail = words.pop
"#{words.join(', ')} #{conjunction} #{tail}"
end
end
end |
FactoryGirl.define do
factory :note do
identity nil
kind 'note'
trait :followup do
kind 'followup'
end
trait :reason do
kind 'reason'
end
factory :note_followup, traits: [:followup]
factory :note_reason, traits: [:reason]
end
end
|
require 'hpricot'
class Page < ActiveRecord::Base
IMAGE_ATTRIBUTES = ['src', 'alt']
ALLOWED_TAGS = ["div", "img"]
belongs_to :site, :autosave => true, :validate => true
validates_presence_of :path
validates_uniqueness_of :path, :scope => :site_id
validate :permission
named_scope :enabled, :conditions => { :enabled => true }
def owner
site.owner
end
def permission
errors.add_to_base "can't add anymore" unless owner.can_add_page?
end
def url
File.join(site.http_url, path)
end
def sections
elements(false).map { |element| element.inner_html }
end
def sections=(htmls)
update_elements(false, htmls) do |element, html|
element.inner_html = html
end
end
def images
elements(true).map do |element|
result = {}
IMAGE_ATTRIBUTES.each { |k| result[k] = element[k] || '' }
result
end
end
def empty?
sections.empty? && images.empty?
end
def images=(elements)
update_elements(true, elements) do |img, attributes|
attributes.each { |k,v| img.attributes[k.to_s] = v }
end
end
def has_suspicious_sections?
elements(false).any? { |e| !ALLOWED_TAGS.include?(e.pathname) }
end
def html_valid?
((document / '.editfu') - nodes).empty?
end
def allowed_tags_with_styleclass
ALLOWED_TAGS.map{ |t| "#{t}.editfu" }
end
protected
def before_save
self.path = self.path.strip.sub(/^\//, '').sub(/\/$/, '')
end
private
def document
@document ||= Hpricot(content)
end
def nodes
(document / allowed_tags_with_styleclass.join(", "))
end
def elements(img)
nodes.select do |e|
!nested_node?(e, nodes) && (e.pathname == 'img') == img
end
end
def nested_node?(node, nodes)
par = node.parent
while par do
return true if nodes.include?(par)
par = par.parent
end
end
def update_elements(img, values)
elements(img).each_with_index do |element, index|
yield element, values[index]
end
self.content = document.to_html
end
end
# == Schema Information
#
# Table name: pages
#
# id :integer(4) not null, primary key
# site_id :integer(4) not null
# path :string(255) not null
# content :text
# enabled :boolean(1) default(TRUE), not null
#
|
OmniAuth.config.logger = Rails.logger
Rails.application.config.middleware.use OmniAuth::Builder do
provider :google_oauth2, ENV['GOOGLE_OAUTH2_ID'], ENV['GOOGLE_OAUTH2_SECRET'], {application_name: ENV['APPLICATION_NAME'], application_version: ENV['APPLICATION_VERSION'], scope: 'userinfo.email,userinfo.profile,calendar', access_type: 'online', prompt: 'select_account',client_options: {ssl: {ca_file: Rails.root.join("cacert.pem").to_s}}}
provider :facebook, ENV['FACEBOOK_KEY'], ENV['FACEBOOK_SECRET']
provider :microsoft_live, ENV['MICROSOFT_LIVE_KEY'], ENV['MICROSOFT_LIVE_SECRET'], {application_name: ENV['APPLICATION_NAME'], application_version: ENV['APPLICATION_VERSION'], scope: 'wl.basic,wl.emails'}
provider :windowslive, ENV['MICROSOFT_LIVE_KEY'], ENV['MICROSOFT_LIVE_SECRET'], {application_name: ENV['APPLICATION_NAME'], application_version: ENV['APPLICATION_VERSION'], scope: 'wl.basic,wl.emails'}
provider :amazon, ENV['AWS_ID_KEY'], ENV['AWS_ID_SECRET'], {application_name: ENV['APPLICATION_NAME'], application_version: ENV['APPLICATION_VERSION']}
end
# thrown this in here to overwrite omniauth strategy
require "oauth2"
require "omniauth"
require "securerandom"
require "socket" # for SocketError
require "timeout" # for Timeout::Error
module OmniAuth
module Strategy # rubocop:disable ModuleLength
def full_host
case OmniAuth.config.full_host
when String
OmniAuth.config.full_host
when Proc
OmniAuth.config.full_host.call(env)
else
# in Rack 1.3.x, request.url explodes if scheme is nil
if request.scheme && request.url.match(URI::ABS_URI)
uri = URI.parse(request.url.gsub(/\?.*$/, ''))
uri.path = ''
# sometimes the url is actually showing http inside rails because the
# other layers (like nginx) have handled the ssl termination.
uri.scheme = 'https' if ssl? # rubocop:disable BlockNesting
uri.to_s
else ''
end
end
end
end
module Strategies
# Authentication strategy for connecting with APIs constructed using
# the [OAuth 2.0 Specification](http://tools.ietf.org/html/draft-ietf-oauth-v2-10).
# You must generally register your application with the provider and
# utilize an application id and secret in order to authenticate using
# OAuth 2.0.
class OAuth2
include OmniAuth::Strategy
def callback_url
ENV["OAUTH_CALLBACK_HOST"] + script_name + callback_path + query_string
end
def callback_phase # rubocop:disable AbcSize, CyclomaticComplexity, MethodLength, PerceivedComplexity
error = request.params["error_reason"] || request.params["error"]
if error
fail!(error, CallbackError.new(request.params["error"], request.params["error_description"] || request.params["error_reason"], request.params["error_uri"]))
elsif (session["omniauth.origin"].present? && request.host == URI.parse(session["omniauth.origin"]).host) && !options.provider_ignores_state && (request.params["state"].to_s.empty? || request.params["state"] != session.delete("omniauth.state"))
fail!(:csrf_detected, CallbackError.new(:csrf_detected, "CSRF detected"))
else
self.access_token = build_access_token
self.access_token = access_token.refresh! if access_token.expired?
super
end
rescue ::OAuth2::Error, CallbackError => e
fail!(:invalid_credentials, e)
rescue ::Timeout::Error, ::Errno::ETIMEDOUT => e
fail!(:timeout, e)
rescue ::SocketError => e
fail!(:failed_to_connect, e)
end
end
end
end |
#!/usr/bin/env ruby
class Solution14
def initialize
@counts_hash = Hash.new
@counts_hash[1] = 0
end
def collatz(n)
if n % 2 == 0
c = n / 2
else
c = 3 * n + 1
end
if !@counts_hash[c].nil?
@counts_hash[n] = @counts_hash[c] + 1
return @counts_hash[n]
else
@counts_hash[n] = collatz(c) + 1
end
end
def longest_sequence_in_range(r)
r.each do |i|
collatz i
end
@counts_hash.max_by{ |k,v| v }[0]
end
end
puts Solution14.new.longest_sequence_in_range(1..1e6.to_i)
|
RSpec.describe "Addition" do
it "adds to numbers" do
expect(1 + 1).to eq 2
end
end
|
# encoding: utf-8
# Code generated by Microsoft (R) AutoRest Code Generator 1.0.1.0
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
module MobileCenterApi
module Models
#
# Device Set
# The name and devices of the device set
#
class DeviceSet
# @return [String] Identifier of the device set
attr_accessor :id
# @return [Float] The number of manufacturers in the device set's device
# selection
attr_accessor :manufacturer_count
# @return [String] Name of the device set
attr_accessor :name
# @return [String] Short ID of the device set's device selection
attr_accessor :short_id
# @return [DeviceSetOwner]
attr_accessor :owner
# @return [Float] The number of os versions in the device set's device
# selection
attr_accessor :os_version_count
# @return [Array<DeviceConfiguration>]
attr_accessor :device_configurations
#
# Mapper for DeviceSet class as Ruby Hash.
# This will be used for serialization/deserialization.
#
def self.mapper()
{
required: false,
serialized_name: 'DeviceSet',
type: {
name: 'Composite',
class_name: 'DeviceSet',
model_properties: {
id: {
required: true,
serialized_name: 'id',
type: {
name: 'String'
}
},
manufacturer_count: {
required: false,
serialized_name: 'manufacturerCount',
type: {
name: 'Double'
}
},
name: {
required: true,
serialized_name: 'name',
type: {
name: 'String'
}
},
short_id: {
required: true,
serialized_name: 'shortId',
type: {
name: 'String'
}
},
owner: {
required: true,
serialized_name: 'owner',
type: {
name: 'Composite',
class_name: 'DeviceSetOwner'
}
},
os_version_count: {
required: false,
serialized_name: 'osVersionCount',
type: {
name: 'Double'
}
},
device_configurations: {
required: true,
serialized_name: 'deviceConfigurations',
type: {
name: 'Sequence',
element: {
required: false,
serialized_name: 'DeviceConfigurationElementType',
type: {
name: 'Composite',
class_name: 'DeviceConfiguration'
}
}
}
}
}
}
}
end
end
end
end
|
class ApplicationController < ActionController::Base
include ScramUtils
helper_method :current_holder
protect_from_forgery with: :exception
def select_team
authenticate_user!
if current_user.current_team.nil?
redirect_to teams_path, alert: t('teams.no-selection')
end
end
rescue_from ScramUtils::NotAuthorizedError do |exception|
respond_to do |format|
format.json { head :forbidden }
format.html { redirect_to root_path, :alert => "You are not authorized to perform that action at this time. Please try signing in!" }
end
end
end
|
class LeadsController < ApplicationController
def new
@lead = Lead.new
end
def create
@lead = Lead.new(insightly_params_lead)
if @lead.save
InsightlyWorker.perform_async(@lead.id)
EmailWorker.perform_async(@lead.id)
flash[:success] = "Success! I will get in contact with you soon!"
redirect_to root_path
else
render :new
end
end
private
def insightly_params_lead
params.require(:lead).permit(
:first_name,
:last_name,
:title,
:organization_name,
:phone_number,
:email,
:training_solution,
:training_solution_description)
end
end
|
# Generator class will create HTML
#
require 'erb'
class Generator
attr_reader :max_images
def initialize()
@max_images = 10
end
def getImageRangeTo(list, from)
to = from + @max_images - 1
to = from + list.size - 1 if list.size < @max_images
return to
end
def getCurrentLink(list, from)
to = getImageRangeTo(list, from)
return "images#{from}-#{to}.html"
end
def getPrevLink(list, from)
return "" if from < @max_images
return "images#{from - @max_images}-#{from - 1}.html"
end
def getNextLink(list, from)
current_to = getImageRangeTo(list, from)
return "" if from + @max_images - 1 > current_to
return "" if list.size == current_to
to = from + @max_images * 2 - 1
to = from + list.size - 1 if list.size < @max_images * 2
return "images#{from + @max_images}-#{to}.html"
end
# create image html from images in source folder.
# return list of created html files.
def create_image_html(source, destination, images)
imagelist = images.dup
createdlist = []
image_from = 1
prev_link = ""
next_link = ""
until imagelist.empty?
filename = getCurrentLink(imagelist, image_from)
image_title = File.basename(filename, ".*")
prev_link = getPrevLink(imagelist, image_from)
next_link = getNextLink(imagelist, image_from)
image_src = imagelist.shift(@max_images)
e = ERB.new(File.read("./template/images.html.erb"), nil, '-')
#puts e.result(binding)
File.open("#{destination}/#{filename}", "w") { |f|
f.puts e.result(binding)
}
createdlist.push (filename)
image_from += @max_images
end
createdlist
end
def create_index_html(fs, path, rpath, createdlist, imagelist)
destination = "#{path}/#{rpath}"
page_title = rpath
# create html tree
# parent folder
parent_name = ""
current_name = ""
slash_pos = rpath.rindex("/")
if slash_pos
parent_name = rpath[0, slash_pos]
parent_name = ".." if parent_name.empty?
current_name = rpath[slash_pos, 256]
end
child_folders = createdlist.dup
printf "#{rpath} : #{parent_name} | #{current_name}\n"
# create image thumbnail list
image_src = fs[:images].dup
image_link = []
image_src.size.times do |i|
image_link.push(imagelist[i / @max_images])
end
e = ERB.new(File.read("./template/index.html.erb"), nil, '-')
File.open("#{destination}/index.html", "w") { |f|
f.puts e.result(binding)
}
end
# return true if html is created including child folder
def output(fs, path, rpath = "")
#puts fs
created = false
createdlist = []
# output child html
fs[:folders].each {|folder|
created = true if output(folder, path, folder[:rpath])
createdlist.push(folder[:rpath].slice(rpath.size, folder[:rpath].size)) if created
}
source = "#{fs[:root]}/#{fs[:rpath]}"
destination = "#{path}/#{rpath}"
# generate imageXX-YY.html
if not fs[:images].empty?
print "generate image.html in #{destination}\n"
imagelist = create_image_html(source, destination, fs[:images])
created = true
end
# generate index.html
if created
print "generate index.html in #{destination}\n"
create_index_html(fs, path, rpath, createdlist, imagelist)
end
created
end
end
|
class Exam < ApplicationRecord
has_many :student_exam_results
has_many :students, through: :student_exam_results
end
|
module DayBuilder
class Week
attr_reader :user
attr_accessor :options
def initialize(user, options = {})
@user = user
@options = options
end
def build
start_day = @options.key?(:start) ? DateTime.parse(@options[:start]) : user.start_of_week
final_day = start_day + 7.days
current_day = start_day.dup.beginning_of_day
sleep_deviation_correction = 120
midnight_offset = 0
while current_day != final_day
TimeTable.build(current_day, user) do |time_table|
# Pre-adjustments
# 6 is saturday
work_tag = case current_day.wday
when 1..5
'work:runa:squad_ron'
else
'projects:birl'
end
fill_start_day_tag = case current_day.wday
when 1
'work:runa:squad_ron'
when 2..5
'projects:birl'
else
nil
end
fill_end_day_tag = case current_day.wday
when 0
'work:runa:squad_ron'
when 1..4
'projects:birl'
else
nil
end
# Times
if sleep_deviation_correction > 0
time_table.timelog(tag: fill_start_day_tag,
duration: "#{sleep_deviation_correction}min")
end
time_table.timelog(duration: '1h30min',
tag: 'study:lightless')
time_table.timelog(duration: '8h30min',
tag: 'life:sleep')
time_table.skip '30min'
time_table.timelog(duration: '3h30min',
tag: work_tag)
time_table.timelog(duration: '2h',
tag: 'progressions:home_training')
time_table.timelog(duration: '3h30min',
tag: work_tag)
time_table.timelog(duration: '1h30min',
tag: 'chores:prepare_for_tomorrow')
time_table.timelog(finish: '00:00',
tag: fill_end_day_tag) if fill_end_day_tag
sleep_deviation_correction -= 30 if sleep_deviation_correction > midnight_offset
end
current_day = (current_day.dup + 1.day).beginning_of_day
end
end
end
end
|
class ChangeAttachmentAttributes < ActiveRecord::Migration
def up
remove_column :attachments, :conversation_file_name
remove_column :attachments, :conversation_content_type
remove_column :attachments, :conversation_file_size
remove_column :attachments, :conversation_updated_at
add_column :attachments, :conversation_file_name, :string
add_column :attachments, :conversation_content_type, :string
add_column :attachments, :conversation_file_size, :string
add_column :attachments, :conversation_updated_at, :datetime
end
def down
end
end
|
# -*- encoding : utf-8 -*-
module BanksHelper
def banks; Hash[Bank::BANKS.map{|k,v| ["#{k} — #{v}".html_safe,k]}] end
end
|
class Product < SnapshotCluster
cluster_of :product_snapshots
has_signature :recommendation
def get_all_products
prod_set = Set.new
snapshots.each do |snap|
prod_set.add(snap.get_product_title)
end
puts "\n---"
prod_set.each do |prod|
puts prod
end
puts "---"
return prod_set
end
def self.label_all_snapshot_with_match_group
Product.each do |p|
p.snapshots.each do |sn|
sn.tmp_match_group = p.match_group
sn.save
end
end
end
end
|
require "cinch"
require "open-uri"
require "json"
class Greeter
include Cinch::Plugin
match /hello$/, method: :greet
def greet(m)
m.reply "Hi there"
end
end
class LibreFM
include Cinch::Plugin
match /np\ ?(.*)/, method: :scrobble
def snark(m)
nick = m.user.nick
data = open("https://libre.fm/2.0/?method=user.getrecenttracks&user=#{nick}&page=1&limit=1&format=json") { |f| JSON.parse f.read }
m.reply "Sorry #{nick}, but I cannot grok LibreFM scrobbles just yet :("
end
def scrobble(m, handle)
if handle.strip.empty?
nick = m.user.nick
else
nick = handle
end
data = open("https://libre.fm/2.0/?method=user.getrecenttracks&user=#{nick}&limit=1&format=json") { |f| JSON.parse f.read }
m.reply "#{nick}'s last scrobbled track was #{data["recenttracks"]["track"]["name"]} by #{data["recenttracks"]["track"]["artist"]["#text"]}"
end
end
bot = Cinch::Bot.new do
configure do |c|
c.nick = "eebrah|bot"
c.server = "chat.freenode.net"
c.channels = ["#nairobilug"]
c.plugins.plugins = [LibreFM]
c.plugins.prefix = /^:/
end
end
bot.start
|
class UrlIsReserved < ActiveRecord::Migration[5.1]
def change
rename_column :competitor_products, :url, :amazon_url
rename_column :products, :url, :amazon_url
end
end
|
# We want to know the index of the vowels in a given word, for example, there are two vowels in the word super (the second and fourth letters).
#
# So given a string "super", we should return a list of [2, 4].
#
# Some examples:
#
# Mmmm => []
# Super => [2,4]
# Apple => [1,5]
# YoMama -> [1,2,4,6]
# NOTE: Vowels in this context refers to English Language Vowels - a e i o u y
#
# NOTE: this is indexed from [1..n] (not zero indexed!)
def vowel_indices(word)
result = []
vowels = ['a', 'e', 'i', 'o', 'u', 'y']
Array.new(0).tap {|arr| word.downcase.split('').each_with_index {|char, index| result << index + 1 if vowels.include? char}}
result
end
vowel_indices('super')
|
Rails.application.routes.draw do
get '/restaurants', to: "restaurants#index"
get '/restaurants/new', to: "restaurants#new"
post '/restaurants', to: "restaurants#create"
get '/restaurants/:id', to: "restaurants#show", as: :restaurant
get '/restaurants/:id/edit', to: "restaurants#edit", as: :edit_restaurant
patch '/restaurants/:id', to: "restaurants#update"
delete '/restaurants/:id', to: "restaurants#destroy", as: :delete_restaurant
get '/restaurants/:restaurant_id/reviews/new', to: "reviews#new", as: :new_restaurant_review
post '/restaurants/:restaurant_id/reviews', to: "reviews#create", as: :restaurant_reviews
# For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
end
# Rails.application.routes.draw do
# resources :restaurants do
# resources :reviews, only: [ :index, :new, :create ]
# end
# resources :reviews, only: [ :show, :edit, :update, :destroy ]
# end
|
class AddUsers < ActiveRecord::Migration
def change
add_column :users, :users_admin, :boolean
add_column :users, :email, :string
end
end
|
module MDML
class Renderer
def self.render(tree, context)
new.render(tree, context)
end
def render(tree, context)
rendered = ''
if !tree.nil?
tree.each do |node|
rendered += _render_node(node, context)
end
end
rendered
end
private
def _render_node(node, context, process = true)
output = ''
if node.is_a?(Hash)
if node[:name] == 'for'
collection = context[node[:collection]]
collection.each do |item|
context[node[:item]] = item
output += _render_node(node[:children], context, process)
end
elsif ['if','unless','case'].include?(node[:name])
node[:conditions].each do |condition|
if true
output += _render_node(condition[:children], context, process)
end
end
elsif node[:name] == 'raw'
output += _render_node(node[:children], context, false)
end
elsif node.is_a?(Array)
node.each do |item|
output += _render_node(item, context, process)
end
elsif node.is_a?(String)
output += _interpolate(node, context, process)
end
output
end
def _interpolate(value, context, process)
return nil if value.nil?
output = value
if process
value.scan(/\{\{([^\}]*)\}\}/).each do |match|
output = output.gsub("{{#{match[0]}}}", context[match[0].strip].to_s)
end
else
value.scan(/\{\{\{([^\}]*)\}\}\}/).each do |match|
output = output.gsub("{{{#{match[0]}}}}", context[match[0].strip].to_s)
end
end
output
end
end
end |
class ModifyAttachments < ActiveRecord::Migration
def change
change_table :posts do |t|
t.remove :attachment
end
change_table :attachments do |t|
t.belongs_to :post, index: true
end
end
end
|
require 'json'
require 'json_builder/member'
module JSONBuilder
class Compiler
class << self
# Public: The helper that builds the JSON structure by calling the
# specific methods needed to build the JSON.
#
# args - Any number of arguments needed for the JSONBuilder::Compiler.
# block - Yielding a block to generate the JSON.
#
# Returns a String.
def generate(*args, &block)
options = args.extract_options!
compiler = self.new(options)
compiler.compile(*args, &block)
compiler.finalize
end
end
attr_accessor :members
attr_accessor :array
attr_accessor :scope
attr_accessor :callback
attr_accessor :pretty_print
# Needed to allow for the id key to be used
undef_method :id if methods.include? 'id'
# Public: Creates a new Compiler instance used to hold any and
# all JSONBuilder::Member objects.
#
# options - Hash of options used to modify JSON output.
#
# Examples
#
# json = JSONBuilder::Compiler.new(:callback => false)
# json.compile do
# name 'Garrett'
# end
# json.finalize
# # => {"name": "Garrett"}
#
# Returns instance of JSONBuilder::Compiler.
def initialize(options={})
@_members = []
@_scope = options.fetch(:scope, nil)
@_callback = options.fetch(:callback, true)
@_pretty_print = options.fetch(:pretty, false)
# Only copy instance variables if there is a scope and presence of Rails
copy_instance_variables_from(@_scope) if @_scope
end
# Public: Takes a block to generate the JSON structure by calling method_missing
# on all members passed to it through the block.
#
# args - An array of values passed to JSONBuilder::Value.
# block - Yielding a block to generate the JSON.
#
# Returns nothing.
def compile(*args, &block)
instance_exec(*args, &block)
end
# Public: Takes a set number of items to generate a plain JSON array response.
#
# Returns instance of JSONBuilder::Elements.
def array(items, &block)
@_array = Elements.new(@_scope, items, &block)
end
# Public: Called anytime the compiler is passed JSON keys,
# first checks to see if the parent object contains the method like
# a Rails helper.
#
# key_name - The key for the JSON member.
# args - An array of values passed to JSONBuilder::Value.
# block - Yielding any block passed to the element.
#
# Returns nothing.
def method_missing(key_name, *args, &block)
if @_scope.respond_to?(key_name) && !ignore_scope_methods.include?(key_name)
@_scope.send(key_name, *args, &block)
else
key(key_name, *args, &block)
end
end
# Public: Generates the start of the JSON member. Useful if the key you are
# generating is dynamic.
#
# key - Used to generate the JSON member's key. Can be a String or Symbol.
# args - An array of values passed to JSONBuilder::Value.
# block - Yielding any block passed to the element.
#
# Examples
#
# key :hello, 'Hi'
# # => "hello": "Hi"
#
# key "item-#{rand(0, 500)}", "I'm random!"
# # => "item-250": "I'm random!"
#
# Returns instance of JSONBuilder::Member.
def key(key_name, *args, &block)
member = Member.new(key_name, @_scope, *args, &block)
@_members << member
member
end
# Public: Combines the output of the compiled members and the change
# there is a JSONP callback. This is what is returned in the response.
#
# Returns a String.
def finalize
include_callback to_s
end
# Public: Gathers the JSON structure and calls it's compiler within each
# instance.
#
# Returns a String.
def to_s
@_array ? @_array.to_s : "{#{@_members.collect(&:to_s).join(', ')}}"
end
private
# Private: Determines whether or not to include a JSONP callback in
# the response.
#
# json - The String representation of the JSON structure.
#
# Returns a String.
def include_callback(json)
@_callback && request_params[:callback] ? "#{request_params[:callback]}(#{pretty_print(json)})" : pretty_print(json)
end
# Private: Determines whether or not to pass the string through the a
# JSON prettifier to help with debugging.
#
# json - The String representation of the JSON structure.
#
# Returns a String.
def pretty_print(json)
@_pretty_print ? JSON.pretty_generate(JSON[json]) : json
end
# Private: Contains the params from the request.
#
# Returns a Hash.
def request_params
@_scope.respond_to?(:params) ? @_scope.params : {}
end
# Private: Takes all instance variables from the scope passed to it
# and makes them available to the block that gets compiled.
#
# object - The scope which contains the instance variables.
# exclude - Any instance variables that should not be set.
#
# Returns nothing.
def copy_instance_variables_from(object, exclude = []) #:nodoc:
vars = object.instance_variables.map(&:to_s) - exclude.map(&:to_s)
vars.each { |name| instance_variable_set(name.to_sym, object.instance_variable_get(name)) }
end
# Private: Array of instance variable names that should not be set for
# the scope.
#
# Returns an Array of Symbols.
def ignore_scope_methods
[:id]
end
end
end
|
class Web::WelcomeController < Web::ApplicationController
def index
@articles = Article.includes(:authors).published
@main_video = Video.main.last
@cool_videos = Video.cool.last 2
end
end
|
class FontSahitya < Formula
head "https://github.com/google/fonts.git", verified: "github.com/google/fonts", branch: "main", only_path: "ofl/sahitya"
desc "Sahitya"
homepage "https://fonts.google.com/specimen/Sahitya"
def install
(share/"fonts").install "Sahitya-Bold.ttf"
(share/"fonts").install "Sahitya-Regular.ttf"
end
test do
end
end
|
require 'spec_helper'
describe Snippet do
def reset_snippet(options = {})
@valid_attributes = {
:id => 1,
:title => "RSpec is great for testing too"
}
@snippet.destroy! if @snippet
@snippet = Snippet.create!(@valid_attributes.update(options))
end
before(:each) do
reset_snippet
end
context "validations" do
it "rejects empty title" do
Snippet.new(@valid_attributes.merge(:title => "")).should_not be_valid
end
it "rejects non unique title" do
# as one gets created before each spec by reset_snippet
Snippet.new(@valid_attributes).should_not be_valid
end
end
it 'should return the page it is attached' do
@snippet.pages.should be_empty
page = Page.create!(:title => 'Page')
2.times do
part = PagePart.create!(:title => 'Other part', :body => "OTHER PART BODY", :page_id => Page.create!(:title => 'Other Page').id)
part.snippets << @snippet
end
@snippet.pages.should have(2).pages
@snippet.pages.each do |p|
p.title.should_not == page.title
end
end
end
|
unless defined?(::ApplicationFilterContext)
class ApplicationFilterContext < Datapimp::Filterable::Context
end
end
class FilterContext < ApplicationFilterContext
cached
def admin?
user.admin?
end
def sort_by
params.fetch(:sort_by, nil)
end
def limit
params.fetch(:limit, 150)
end
end
|
module Member
class BankCardsController < JsonController
def index
user = Users::User.find(params[:member_id])
@cards = user.bank_cards
end
end
end
|
class CredibilityScoreJob < ApplicationJob
def perform(id)
applicant = Applicant.find_by(id: id)
score = Credibility.new(applicant).get_score if applicant
applicant.update(credibility_score: score) if applicant && score.positive?
end
end
|
# Main entry point into the application.
module LifeGameViewer
class Main
def self.view_sample
LifeGameViewerFrame.view_sample
end
def self.view(model)
LifeGameViewerFrame.new(model).visible = true
end
end
end
|
require "rails_helper"
describe RemoteResources::IndividualResource do
let(:example_data) {
o_file = File.open(File.join(Rails.root, "spec/data/remote_resources/individual.xml"))
data = o_file.read
o_file.close
data
}
describe "given a requestable object and an individual id url" do
let(:requestable) { double }
let(:individual_id) { "an individual id" }
let(:request_properties) {
{
:routing_key => "resource.individual",
:headers => {
:individual_id => individual_id
}
}
}
describe "when the remote resource does not respond" do
before :each do
allow(requestable).to receive(:request).with(request_properties, "", 30).and_raise(Timeout::Error)
end
it "should return a 503" do
rcode, body = RemoteResources::IndividualResource.retrieve(requestable, individual_id)
expect(rcode.to_s).to eq "503"
end
end
describe "for an individual uri which does not exist" do
let(:response_props) {
double(:headers => {
:return_status => "404"
})
}
before :each do
allow(requestable).to receive(:request).with(request_properties, "", 30).and_return([nil, response_props, ""])
end
it "should return a 404" do
rcode, body = RemoteResources::IndividualResource.retrieve(requestable, individual_id)
expect(rcode.to_s).to eq "404"
end
end
describe "for an existing resource" do
let(:response_props) {
double(:headers => {
:return_status => "200"
})
}
let(:resource_response_body) {
o_file = File.open(File.join(Rails.root, "spec/data/remote_resources/individual.xml"))
data = o_file.read
o_file.close
data
}
before :each do
allow(requestable).to receive(:request).with(request_properties, "", 30).and_return([nil, response_props, example_data])
end
it "should have a response code of 200" do
rcode, body = RemoteResources::IndividualResource.retrieve(requestable, individual_id)
expect(rcode.to_s).to eq "200"
end
it "should return the parsed payload" do
rcode, returned_resource = RemoteResources::IndividualResource.retrieve(requestable, individual_id)
expect(returned_resource.kind_of?(RemoteResources::IndividualResource)).to eq true
end
end
end
describe "given example data to parse" do
subject { RemoteResources::IndividualResource.parse(example_data, :single => true) }
it "should have the correct hbx_member_id" do
expect(subject.hbx_member_id).to eq("18941339")
end
it "should have the correct names" do
expect(subject.name_first).to eq "Sulis"
expect(subject.name_last).to eq "Minerva"
expect(subject.name_middle).to eq "J"
expect(subject.name_pfx).to eq "Dr."
expect(subject.name_sfx).to eq "of Bath"
end
it "should have the correct demographic information" do
expect(subject.ssn).to eq "321470519"
expect(subject.dob).to eq Date.new(1973, 7, 24)
expect(subject.gender).to eq "female"
end
it "should have the correct addresses" do
address = subject.addresses.first
expect(address.address_kind).to eq "home"
expect(address.address_line_1).to eq "2515 I Bath Street NW"
expect(address.address_line_2).to eq "Apt. Whatever"
expect(address.location_city_name).to eq "Washington"
expect(address.location_state_code).to eq "DC"
expect(address.postal_code).to eq "20037"
end
it "should have the correct emails" do
email = subject.emails.first
expect(email.email_kind).to eq "home"
expect(email.email_address).to eq "sminerva@gmail.com"
end
it "should have the correct phones" do
first_phone = subject.phones.first
second_phone = subject.phones.last
expect(first_phone.phone_kind).to eq "home"
expect(first_phone.full_phone_number).to eq "5882300123"
expect(first_phone.ignored?).to eq false
expect(second_phone.ignored?).to eq true
end
end
describe "when that record does not exist in the db" do
let(:member_query) { double(:execute => nil) }
subject { RemoteResources::IndividualResource.parse(example_data, :single => true) }
it "should not exist" do
allow(::Queries::PersonByHbxIdQuery).to receive(:new).with("18941339").and_return(member_query)
expect(subject.exists?).to be false
end
end
describe "when that record does exist in the db" do
let(:member_query) { double(:execute => double) }
subject { RemoteResources::IndividualResource.parse(example_data, :single => true) }
it "should exist" do
allow(::Queries::PersonByHbxIdQuery).to receive(:new).with("18941339").and_return(member_query)
expect(subject.exists?).to be true
end
end
end
|
hash = {
foo: 'bar'
}
pp hash[:boo] # => nil
h = Hash.new { |h, k| h[k] = k.to_i * 10 }
pp h[10] # => 100
pp hash[:foo] # => 'bar'
# Hash クラス実装の空想:
# class Hash
# def initialize(ifnone = nil)
# @ifnone = ifnone
# self # 自分自身を返す
# end
# def [](key)
# return @ifnone if self[key].nil?
# end
# end
hash =
Hash.new do |hash, key|
puts "Hello, #{key}"
puts "Hello, #{hash}"
hash[key] = []
puts "Hello, #{hash}"
end
hash[0]
hash[:foo] = 'bar'
foo = lambda do |name|
puts "Hello, #{name}"
end
foo.call('bar')
# { :name => "hana", :age => 20} do |hash, key|
count = 0
injection_hash = Hash.new do |hash, key|
hash[key] = []
count += 1
end
injection_hash[0]
|
class Public::SharedListsController < ApplicationController
skip_before_action :authenticate_user!, only: :show
before_action :find_shared_list, only: :show
layout "public"
def show
@documents = DocumentDecorator.decorate_collection(@shared_list.documents.validated.includes(attachment_attachment: :blob))
@folders = @shared_list.folders.with_validated_documents
end
private
def find_shared_list
@shared_list = SharedList.find_by(code: params[:code])
authorize([:public, @shared_list])
end
end
|
require 'yaml'
require 'ostruct'
module Monexa
def self.config_file
path = File.join(ROOT, 'config')
path = '.' unless File.directory?(path)
File.expand_path(File.join(path, CONFIG_NAME))
end
def self.init_config(config = nil)
path = File.expand_path(config||config_file)
raise "Failed to locate configuration file '#{CONFIG_NAME}', place in 'config/' or '.'" unless File.readable?(path)
Monexa::log.debug "Using configuration file '#{path}'"
@config = OpenStruct.new(YAML.load_file(path)) unless @config
set_defaults(@config)
end
def self.set_defaults(config)
config.dry_run ||= false
config
end
def self.config
@config ||= init_config
end
def self.config=(config)
init_config(config)
end
end |
require 'spec_helper'
describe 'omnitruck instance users' do
describe user('omnitruck') do
it { should exist }
it { should belong_to_group 'omnitruck' }
it { should have_home_directory '/srv/omnitruck' }
it { should have_login_shell '/bin/false' }
end
[
'/srv/omnitruck',
'/srv/omnitruck/shared',
'/srv/omnitruck/shared/pids'
].each do |f|
describe file(f) do
it { should be_owned_by 'omnitruck' }
it { should be_grouped_into 'omnitruck' }
end
end
end
|
require 'byebug'
class PolyTreeNode
attr_accessor :parent, :children
attr_reader :value
def initialize(value)
@value = value
@parent = nil
@children = []
end
def parent=(new_parent)
# debugger
if new_parent == nil
@parent.children.delete(self) if @parent
@parent = nil
elsif new_parent != @parent
@parent.children.delete(self) if @parent
@parent = new_parent
new_parent.children.push(self) if !new_parent.children.include?(self)
end
end
def add_child(new_child)
new_child.parent = self
self.children << new_child
end
def remove_child(dead_child)
dead_child.parent = nil
raise ArgumentError if dead_child.parent == nil
self.children.delete(dead_child)
end
def dfs(target)
return self if self.value == target
self.children.each do |child|
search_result_node = child.dfs(target)
return search_result_node if !search_result_node.nil?
end
nil
end
def bfs(descendant)
# create a queue and add node to explore
queue = []
queue << self
until queue.empty? || queue.first.value == descendant
queue.shift.children.each do |child|
queue << child
end
end
queue.first
end
end
|
# encoding: utf-8
$: << 'RspecTests/Generated/head'
require 'rspec'
require '1.0.0/generated/head'
include HeadModule
describe 'Head' do
before(:all) do
@base_url = ENV['StubServerURI']
dummyToken = 'dummy12321343423'
@credentials = MsRest::TokenCredentials.new(dummyToken)
@client = AutoRestHeadTestService.new(@credentials, @base_url)
end
it 'send head 200' do
result = @client.http_success.head200_async().value!
expect(result.body).to be(true)
end
it 'send head 204' do
result = @client.http_success.head204_async().value!
expect(result.body).to be(true)
end
it 'send head 404' do
result = @client.http_success.head404_async().value!
expect(result.body).to be(false)
end
end |
class CreateTweets < ActiveRecord::Migration
def change
create_table :tweets do |t|
t.column :username, :string
t.column :handle, :string
t.column :tweet_text, :string
t.column :user_id, :integer
t.column :hashtag, :string
t.timestamps
end
end
end
|
#練習問題
#好きな数だけ単語の入力をしてもらい(1行に1単語、最後はEnterだけの空行)、 アルファベット順に並べ変えて出力するようなプログラムを書いてみましょう?
##ヒント: 配列を順番に並び替える(ソートする)には 素敵なメソッド sortがあります。 これを使いましょう。
#(訳注:配列 ary の最後に要素 elem を追加するには、ary << elem と 記述します。)
puts "気が済むまで単語をいれてね!"
tango = nil
ary = %w()
while tango != "\n"
tango = gets
ary << tango.chomp
end
puts ary.sort
#• 上のプログラムをsortメソッドなしで 書けますか。プログラミングの大部分は、問題解決にあります。 これはいい練習になります。
puts "気が済むまで単語をいれてね!"
tango = nil
ary = %w()
while tango != "\n"
tango = gets
mae = ary.select {|a| a < tango}
ato = ary.select {|a| a > tango}
ary = (mae << tango.chomp) + ato
end
puts ary
#練習問題
#• 以前、メソッドの章で書いた 目次を表示するプログラムを修正してみましょう。その際、プログラムの最初で 目次の情報(つまり、章の名前やページ番号など)をすべてひとつの配列にしまいます。 その後、その配列から情報を取り出して美しくフォーマットされた目次を出力します。
lineWidth = 40
puts " 目 次 ".center(lineWidth)
puts ""
nakami = [['1章: 数', 'p. 1'], ['2章: 文字', 'p. 72'], ['3章: 変数', 'p. 118']]
nakami.each{|a| puts a[0].ljust(lineWidth/2) + a[1].rjust(lineWidth/2)}
|
class FeatsController < ApplicationController
before_filter :get_user
# GET /feats
# GET /feats.xml
def index
@date = params[:date].present? ? Date.parse(params[:date]) : Date.today
beginning_of_day, end_of_day = @date.beginning_of_day, @date.end_of_day
@feats = @person.feats.all(
:include => :activity,
:conditions => ["activities.start_time > ? and activities.start_time < ?", beginning_of_day, end_of_day])
respond_to do |format|
format.html # index.html.erb
format.xml { render :xml => @feats }
end
end
# GET /feats/1
# GET /feats/1.xml
def show
@feat = @person.feats.find(params[:id])
respond_to do |format|
format.html # show.html.erb
format.xml { render :xml => @feat }
end
end
# GET /feats/new
# GET /feats/new.xml
def new
@feat = @person.feats.new
respond_to do |format|
format.html # new.html.erb
format.xml { render :xml => @feat }
end
end
# GET /feats/1/edit
def edit
@feat = @person.feats.find(params[:id])
end
# POST /feats
# POST /feats.xml
def create
@feat = @person.feats.new(params[:feat])
respond_to do |format|
if @feat.save
format.html { redirect_to([@person, @feat], :notice => 'Feat was successfully created.') }
format.xml { render :xml => @feat, :status => :created, :location => @feat }
else
format.html { render :action => "new" }
format.xml { render :xml => @feat.errors, :status => :unprocessable_entity }
end
end
end
# PUT /feats/1
# PUT /feats/1.xml
def update
@feat = @person.feats.find(params[:id])
level_old = @person.level
if params[:feat][:completed] == '1'
@feat.complete
else
@feat.uncomplete
end
sign = params[:feat][:completed] == '1' ? '+': '-'
has_leveled = @person.level > level_old
respond_to do |format|
format.json { render :json => {
:xpGained => "#{sign}#{@feat.xp}",
:xpTotal => @person.xp,
:next_level_ratio => @person.next_level_ratio,
:extra_life => @person.level_to_string,
:has_leveled => has_leveled,
:completed => @feat.completed,
:streak => @feat.calculate_streak}}
end
end
# DELETE /feats/1
# DELETE /feats/1.xml
def destroy
@feat = @person.feats.find(params[:id])
@feat.destroy
respond_to do |format|
format.html { redirect_to(person_feats_url(@person)) }
format.xml { head :ok }
end
end
private
def get_user
@person = Person.find(params[:person_id]) unless params[:person_id].blank?
end
end
|
require 'rspec'
require 'json'
require_relative '../model/calendario'
require_relative '../model/GestorCalendario'
require_relative '../model/calendario_nombre_existente_error'
require_relative '../model/calendario_sin_nombre_error'
require_relative '../model/calendario_inexistente_error'
describe 'GestorCalendario' do
it 'Borrar Calendario invoca al persistor a borrar calendario' do
persistorDouble = double('Persistor', :borrar_calendario => "borrado")
convertidorJsonObjetoDouble = double('ConvertidorJsonObjeto')
validador = double("Validador", :validar_calendario_existente => "valido")
convertidorObjetoJsonDouble = double("convertidorObjetoJsonDouble")
expect(persistorDouble).to receive(:borrar_calendario).with("calendario1")
expect(validador).to receive(:validar_calendario_existente).with("calendario1")
gestor = GestorCalendario.new(persistorDouble, convertidorJsonObjetoDouble, convertidorObjetoJsonDouble, validador)
gestor.borrarCalendario("calendario1")
end
it 'Obtener CAlendario invoca al persistor a obtener_calendario' do
persistorDouble = double('Persistor', :obtener_calendario_eventos => "{ 'nombre' : 'calendario1' }")
convertidorJsonObjetoDouble = double('ConvertidorJsonObjeto')
validador = double("Validador", :validar_calendario_existente => "ok")
convertidorObjetoJsonDouble = double("convertidorObjetoJsonDouble")
expect(persistorDouble).to receive(:obtener_calendario_eventos).with("calendario1")
gestor = GestorCalendario.new(persistorDouble, convertidorJsonObjetoDouble, convertidorObjetoJsonDouble, validador)
rta = gestor.obtenerCalendario("calendario1")
expect(rta.getRespuesta()).to eq "\"\\\"{ 'nombre' : 'calendario1' }\\\"\""
end
it 'Crear calendario invoca al conversor y al persistor para crearlo' do
calendario = Calendario.new("calendario1")
validador = double("Validador", :validar_crear_calendario => "validado")
convertidorObjetoJsonDouble = double("convertidorObjetoJsonDouble")
persistorDouble = double('Persistor', :crear_calendario => "creado")
convertidorJsonObjetoDouble = double('ConvertidorJsonObjeto', :convertir_calendario_no_array => calendario)
expect(persistorDouble).to receive(:crear_calendario).with(calendario)
gestor = GestorCalendario.new(persistorDouble, convertidorJsonObjetoDouble, convertidorObjetoJsonDouble, validador)
gestor.crearCalendario("calendario1")
end
it 'Crear calendario duplicado error' do
calendario = Calendario.new("calendario1")
validador = double("Validador")
convertidorObjetoJsonDouble = double("convertidorObjetoJsonDouble")
persistorDouble = double('Persistor', :crear_calendario => "creado")
convertidorJsonObjetoDouble = double('ConvertidorJsonObjeto', :convertir_calendario_no_array => calendario)
allow(validador).to receive(:validar_crear_calendario).and_raise(CalendarioNombreExistenteError)
expect(persistorDouble).not_to receive(:crear_calendario).with(calendario)
gestor = GestorCalendario.new(persistorDouble, convertidorJsonObjetoDouble, convertidorObjetoJsonDouble, validador)
response = gestor.crearCalendario("calendario1")
expect(response.getEstado()).to eq 400
expect(response.getRespuesta()).to eq "Ya existe un calendario con el nombre ingresado"
end
it 'Crear calendario sin nombre error' do
calendario = Calendario.new("calendario1")
validador = double("Validador")
convertidorObjetoJsonDouble = double("convertidorObjetoJsonDouble")
persistorDouble = double('Persistor', :crear_calendario => "creado")
convertidorJsonObjetoDouble = double('ConvertidorJsonObjeto', :convertir_calendario_no_array => calendario)
allow(validador).to receive(:validar_crear_calendario).and_raise(CalendarioSinNombreError)
expect(persistorDouble).not_to receive(:crear_calendario).with(calendario)
gestor = GestorCalendario.new(persistorDouble, convertidorJsonObjetoDouble, convertidorObjetoJsonDouble, validador)
response = gestor.crearCalendario("calendario1")
expect(response.getEstado()).to eq 400
expect(response.getRespuesta()).to eq "El calendario ingresado posee el nombre vacio"
end
it 'Obtener CAlendario inexistente error' do
persistorDouble = double('Persistor', :obtener_calendario => "{ 'nombre' : 'calendario1' }")
convertidorJsonObjetoDouble = double('ConvertidorJsonObjeto')
validador = double("Validador")
convertidorObjetoJsonDouble = double("convertidorObjetoJsonDouble")
allow(validador).to receive(:validar_calendario_existente).and_raise(CalendarioInexistenteError)
expect(persistorDouble).not_to receive(:obtener_calendario).with("calendario1")
gestor = GestorCalendario.new(persistorDouble, convertidorJsonObjetoDouble, convertidorObjetoJsonDouble, validador)
rta = gestor.obtenerCalendario("calendario1")
expect(rta.getEstado()).to eq 404
expect(rta.getRespuesta()).to eq "El nombre de calendario ingresado no existe"
end
it 'crear Evento llama al conversor y al persistor' do
evento = Evento.new("Calendario1",
"testEvento",
"fiesta",
DateTime.strptime("2017-03-31T18:00:00-03:00","%Y-%m-%dT%H:%M:%S%z"),
DateTime.strptime("2017-03-31T22:00:00-03:00","%Y-%m-%dT%H:%M:%S%z"),
Recurrencia.new('semanal',
DateTime.strptime("2017-03-31T18:00:00-03:00", "%Y-%m-%dT%H:%M:%S%z")))
convertidorObjetoJsonDouble = double("convertidorObjetoJsonDouble")
persistorDouble = double('Persistor', :crear_evento => "creado")
validador = double('VAlidador')
validadorEvento = double('validadorEvento',:validar_calendario_existente=>true,:validar_duracion_evento_permitida=>true,:validar_fecha_fin_posterior_fecha_inicio=>true,:validar_id_evento_ya_existente=>true,:validar_nombre_evento_ya_existente_en_calendario=>true,:validar_no_superposicion_de_eventos=>true)
convertidorJsonObjetoDouble = double('ConvertidorJsonObjeto', :convertir_evento_no_array => evento)
expect(persistorDouble).to receive(:crear_evento).with(evento)
gestor = GestorCalendario.new(persistorDouble, convertidorJsonObjetoDouble, convertidorObjetoJsonDouble, validador,validadorEvento)
gestor.crearEvento('{
"calendario" : "calendario1",
"id" : "testEvento",
"nombre" : "fiesta",
"inicio" : "2017-03-31T18:00:00-03:00",
"fin" : "2017-03-31T18:00:00-03:00",
"recurrencia" : {
"frecuencia" : "semanal",
"fin" : "2017-03-31T18:00:00-03:00"
}
}')
end
it 'listar eventos de calendario' do
evento = Evento.new("Calendario1",
"testEvento",
"fiesta",
DateTime.strptime("2017-03-31T18:00:00-03:00","%Y-%m-%dT%H:%M:%S%z"),
DateTime.strptime("2017-03-31T22:00:00-03:00","%Y-%m-%dT%H:%M:%S%z"),
Recurrencia.new('semanal',
DateTime.strptime("2017-03-31T18:00:00-03:00", "%Y-%m-%dT%H:%M:%S%z")))
convertidorJsonObjetoDouble = double("convertidorJsonObjetoDouble")
persistorDouble = double('Persistor', :listar_eventos_por_calendario => [evento])
validador = double('VAlidador', :validar_calendario_existente => "validado")
convertidorObjetoJsonDouble = double('ConvertidorObjetoJson', :convertir_eventos => [evento])
validadorEvento = double('ValidadorEvento')
jsondouble = double('JSON', :dump => "convertido")
expect(validador).to receive(:validar_calendario_existente).with("Calendario1")
expect(persistorDouble).to receive(:listar_eventos_por_calendario).with("Calendario1")
expect(jsondouble).to receive(:dump).with([evento])
gestor = GestorCalendario.new(persistorDouble, convertidorJsonObjetoDouble, convertidorObjetoJsonDouble, validador, validadorEvento,jsondouble)
rta = gestor.listarEventosPorCalendario('Calendario1')
expect(rta.getRespuesta()).to eq "convertido"
expect(rta.getEstado()).to eq 200
end
end |
class Category < ApplicationRecord
has_many :categorizes, dependent: :destroy
has_many :posts, through: :categorize
end
|
# frozen_string_literal: true
require 'rails_helper'
RSpec.describe Chat, type: :model do
it { should validate_presence_of(:name) }
it { should validate_presence_of(:privacy) }
it { should allow_values('public', 'private', 'protected').for(:privacy) }
it { should have_secure_password }
it 'is not valid without attributes' do
expect(Chat.new).to_not be_valid
end
it 'validates uniqueness of name' do
create(:chat, name: 'unique', privacy: 'public')
should validate_uniqueness_of(:name)
end
it 'is not valid when set to protected without password' do
expect { create(:chat, privacy: 'protected') }.to raise_error(ActiveRecord::RecordInvalid)
end
it 'is valid when set to protected and a password' do
subject { described_class.new }
subject.name = 'Hop'
subject.privacy = 'protected'
subject.password = 'asd'
expect(subject).to be_valid
end
it 'is valid without name if privacy == direct_message' do
subject { described_class.new }
subject.name = ''
subject.privacy = 'direct_message'
expect(subject).to be_valid
end
it 'is not valid without name if privacy == public' do
subject { described_class.new }
subject.name = ''
subject.privacy = 'public'
expect(subject).to_not be_valid
end
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.