text stringlengths 10 2.61M |
|---|
# frozen_string_literal: true
# rubocop:todo all
module Mongo
module CRUD
# Represents a single CRUD test.
#
# @since 2.0.0
class CRUDTest < CRUDTestBase
# Spec tests have configureFailPoint as a string, make it a string here too
FAIL_POINT_BASE_COMMAND = BSON::Document.new(
'configureFailPoint' => "onPrimaryTransactionalWrite",
).freeze
# Instantiate the new CRUDTest.
#
# data can be an array of hashes, with each hash corresponding to a
# document to be inserted into the collection whose name is given in
# collection_name as configured in the YAML file. Alternatively data
# can be a map of collection names to arrays of hashes.
#
# @param [ Crud::Spec ] crud_spec The top level YAML specification object.
# @param [ Hash | Array<Hash> ] data The documents the collection
# must have before the test runs.
# @param [ Hash ] test The test specification.
#
# @since 2.0.0
def initialize(crud_spec, data, test)
@spec = crud_spec
@data = data
@description = test['description']
@client_options = ::Utils.convert_client_options(test['clientOptions'] || {})
if test['failPoint']
@fail_point_command = FAIL_POINT_BASE_COMMAND.merge(test['failPoint'])
end
if test['operations']
@operations = test['operations'].map do |op_spec|
Operation.new(self, op_spec)
end
else
@operations = [Operation.new(self, test['operation'], test['outcome'])]
end
@expectations = BSON::ExtJSON.parse_obj(test['expectations'], mode: :bson)
if test['outcome']
@outcome = Mongo::CRUD::Outcome.new(BSON::ExtJSON.parse_obj(test['outcome'], mode: :bson))
end
end
attr_reader :client_options
# Operations to be performed by the test.
#
# For CRUD tests, there is one operation for test. For retryable writes,
# there are multiple operations for each test. In either case we build
# an array of operations.
attr_reader :operations
attr_reader :outcome
# Run the test.
#
# The specified number of operations are executed, so that the
# test can assert on the outcome of each specified operation in turn.
#
# @param [ Client ] client The client the test
# should be run with.
# @param [ Integer ] num_ops Number of operations to run.
#
# @return [ Result, Array<Hash> ] The result(s) of running the test.
#
# @since 2.0.0
def run(client, num_ops)
result = nil
1.upto(num_ops) do |i|
operation = @operations[i-1]
target = resolve_target(client, operation)
result = operation.execute(target)
end
result
end
class DataConverter
include Mongo::GridFS::Convertible
end
def setup_test(spec, client)
clear_fail_point(client)
if @data.nil?
# nothing to do
elsif @data.is_a?(Array)
collection = client[spec.collection_name, write_concern: {w: :majority}]
collection.delete_many
collection.insert_many(@data) unless @data.empty?
elsif @data.is_a?(Hash)
converter = DataConverter.new
@data.each do |collection_name, data|
collection = client[collection_name]
collection.delete_many
data = converter.transform_docs(data)
collection.insert_many(data)
end
else
raise "Unknown type of data: #{@data}"
end
setup_fail_point(client)
end
def actual_collection_contents(client)
unless @spec.collection_name
raise ArgumentError, 'Spec does not specify a global collection'
end
client[@spec.collection_name, read_concern: {level: :majority}].find.to_a
end
end
end
end
|
require "rails_helper"
RSpec.describe ZipCode, type: :model do
describe "#coordinates" do
it "returns an array of latitude, longitude" do
latitude = 12.345
longitude = 67.890
zip_code = ZipCode.new(latitude: latitude, longitude: longitude)
expect(zip_code.coordinates).to eq [latitude, longitude]
end
end
end
|
class Blogpicture < ActiveRecord::Base
belongs_to :post
has_attached_file :picture,
style: { medium: "500x400", thumb: "100x100"},
default_url: "/assets/original/portfolio-demo.gif",
url: ":s3_domain_url",
path: "public/admin/posts/:id_:basename.:extension",
storage: :fog,
fog_credentials: {
provider: 'AWS',
region: 'eu-central-1',
aws_access_key_id: ENV["AWS_ACCESS_KEY_ID"],
aws_secret_access_key: ENV["AWS_SECRET_ACCESS_KEY"]
},
fog_directory: ENV["FOG_DIRECTORY"]
validates_attachment_content_type :picture, content_type: /\Aimage\/.*\Z/
end
|
require_relative 'method_documentation'
require_relative 'tagged_markdown'
class Apiculture::AppDocumentation
JOINER = "\n\n"
TEMPLATE_PATH = '/app_documentation_tpl.mustache'
def initialize(app, mountpoint, action_definitions_and_markdown_segments)
@app_title = app.to_s
@mountpoint = mountpoint
@chunks = action_definitions_and_markdown_segments
end
# Generates a Markdown string that contains the entire API documentation
def to_markdown
(['## %s' % @app_title] + to_tagged_markdowns).join(JOINER)
end
# Generates a complete HTML document string that can be saved into a file
def to_html
require 'mustache'
template = File.read(__dir__ + TEMPLATE_PATH)
Mustache.render(template, html_fragment: to_html_fragment)
end
# Generates an HTML fragment string that can be included into another HTML document
def to_html_fragment
to_tagged_markdowns.map(&:to_html).join(JOINER)
end
private
def to_tagged_markdowns
@chunks.map do |action_def_or_doc|
action_def_or_doc.to_tagged_markdown(@mountpoint)
end
end
end
|
# encoding: utf-8
# copyright: 2016, you
# license: All rights reserved
# date: 2016-09-16
# description: The Microsoft Internet Explorer 11 Security Technical Implementation Guide (STIG) is published as a tool to improve the security of Department of Defense (DoD) information systems. Comments or proposed revisions to this document should be sent via e-mail to the following address: disa.stig_spt@mail.mil
# impacts
title 'V-46599 - Navigating windows and frames across different domains must be disallowed (Restricted Sites zone).'
control 'V-46599' do
impact 0.5
title 'Navigating windows and frames across different domains must be disallowed (Restricted Sites zone).'
desc 'Frames navigating across different domains are a security concern, because the user may think they are accessing pages on one site while they are actually accessing pages on another site. It is possible that a website hosting malicious content could use this feature in a manner similar to cross-site scripting (XSS). This policy setting allows you to manage the opening of sub-frames and access of applications across different domains.'
tag 'stig', 'V-46599'
tag severity: 'medium'
tag checkid: 'C-49765r2_chk'
tag fixid: 'F-50369r1_fix'
tag version: 'DTBI129-IE11'
tag ruleid: 'SV-59463r1_rule'
tag fixtext: 'Set the policy value for Computer Configuration -> Administrative Templates -> Windows Components -> Internet Explorer -> Internet Control Panel -> Security Page -> Restricted Sites Zone -> Navigate windows and frames across different domains to Enabled, and select Disable from the drop-down box. '
tag checktext: 'The policy value for Computer Configuration -> Administrative Templates -> Windows Components -> Internet Explorer -> Internet Control Panel -> Security Page -> Restricted Sites Zone -> Navigate windows and frames across different domains must be Enabled, and Disable selected from the drop-down box. Procedure: Use the Windows Registry Editor to navigate to the following key: HKLM\Software\Policies\Microsoft\Windows\CurrentVersion\Internet Settings\Zones\4 Criteria: If the value "1607" is REG_DWORD = 3, this is not a finding.'
# START_DESCRIBE V-46599
describe registry_key({
hive: 'HKLM',
key: 'Software\Policies\Microsoft\Windows\CurrentVersion\Internet Settings\Zones\4',
}) do
its('1607') { should eq 3 }
end
# STOP_DESCRIBE V-46599
end
|
require_relative '../../../config/environment'
require_relative '../option_methods/main_menu_methods'
require 'highline/import'
def user_login_menu
puts "Do you already have an account? (y/n)"
login
end
def login
answer = gets.strip.downcase
case answer
when "y", "yes"
puts "\nGreat!"
login_to_account
when "n", "no"
puts "\nOk, creating a new account is easy!"
create_an_account
else
puts "\nInvalid response."
puts "Please enter yes or no."
login
end
end
def login_to_account
puts "\nPlease enter your username:"
name = gets.strip
if Patient.find_by(name: name)
@patient = Patient.find_by(name: name)
password_authenticate
else
sleep(0.5)
puts "\nThe account you entered doesn't exist.\n"
incorrect_login
end
end
def create_an_account
puts "\nPlease enter a new username:"
puts "(must be between 5 and 20 characters)"
name = gets.strip
if !Patient.find_by(name: name) && name.length >= 5 && name.length <= 20
@patient = Patient.create(name: name)
@patient.save
sleep(0.5)
puts "\nHello, #{@patient.name.split(" ")[0]}\n"
sleep(0.5)
puts "Please choose a password:"
new_password_validate
puts "\nThank you! Would you like to log in now? (y/n)"
choices_after_account_creation
elsif name.length < 5
sleep(0.5)
puts "\nSorry, that's too short."
create_an_account
elsif name.length > 20
sleep(0.5)
puts "\nSorry, that's too long."
create_an_account
else
puts "\nSorry, that username is taken."
puts "You must choose a unique username."
create_an_account
end
end
def check_password_validity(password)
check_string_case(password) && check_string_empty(password) && check_include_integer(password) && check_string_special(password)
end
def new_password_validate
puts "You must include at least one: \nspecial character, upper case letter, lower case letter, AND integer"
password = (ask("") { |q| q.echo = "*" }).strip
# password = gets.strip
if check_password_validity(password)
@patient.password = password
@patient.save
else
puts "Invalid password."
puts "Please enter a new password.\n\n"
new_password_validate
end
end
def incorrect_login
puts "Please choose one:"
puts "1. Try again"
puts "2. Create a new account\n\n"
choice = gets.strip
case choice
when "1"
user_login_menu
when "2"
create_an_account
else
puts "\nInvalid response:"
puts "Please enter 1 or 2.\n\n"
incorrect_login
end
end
def choices_after_account_creation
open_or_not = gets.strip.downcase
case open_or_not
when "y", "yes"
main_menu_methods
when "n", "no"
puts "\nThank you for creating an account. See you soon!"
else
puts "\nInvalid response:"
puts "Please enter yes or no."
choices_after_account_creation
end
end
def password_authenticate
# puts "\nPlease enter your password:"
password = (ask("Please enter your password: ") { |q| q.echo = "*" }).strip
# password = gets.strip
if @patient.authenticate(password)
sleep(0.5)
puts "\n\nWelcome #{@patient.name.split(" ")[0]}"
main_menu_methods
else
puts "\nThe password you entered is incorrect"
puts "Please choose one:"
puts "1. Try again"
puts "2. Create a new account"
validate_password_response
end
end
def validate_password_response
choice = gets.strip
case choice
when "1"
password_authenticate
when "2"
create_an_account
else
puts "\nInvalid response:"
puts "Please enter 1 or 2."
validate_password_response
end
end
|
class TradingStrategyService
MAX_CONSECUTIVE_FAIL_TIMES = 5
DEFAULT_STRATEGY = 'constant'
DEFAULT_PERCENTAGE = 0.005.to_d
attr_reader :trader, :exchange
def initialize(trader:, exchange:)
@trader = trader
@exchange = exchange
end
def open_order_percentage
@open_order_percentage ||= begin
if strategy_config.name == 'constant'
default_percentage
elsif strategy_config.name == 'tier'
tier_percentage
end
end
end
private
def tier_percentage
return default_percentage unless exchange.has_history?
return default_percentage if exchange.last_order_profit?
(consecutive_fail_times + 1) * default_percentage
end
def max_consecutive_fail_times
@max_consecutive_fail_times ||= strategy_config.max_consecutive_fail_times
end
def strategy_config
@strategy_config ||= TradingStrategy.find_by(trader_id: trader.id) || default_trading_strategy
end
def default_trading_strategy
@default_trading_strategy ||= TradingStrategy.new(
trader_id: trader.id,
name: Setting.default_trading_strategy,
max_consecutive_fail_times: Setting.max_consecutive_fail_times
)
end
def default_percentage
@default_percentage ||= exchange.user.first_order_percentage || DEFAULT_PERCENTAGE
end
def consecutive_fail_times
@consecutive_fail_times ||= exchange.continuous_fail_times % max_consecutive_fail_times
end
end |
class Mutations::CreateBreakpoint < GraphQL::Schema::Mutation
argument :description, String, required: true
field :breakpoint, Types::BreakpointType, null: true
def resolve(description:)
{
breakpoint: {
id: "new_uuid",
description: "woooooah #{description}",
timestamp: Time.current
}
}
end
end |
class AddPlanetarySystemToStar < ActiveRecord::Migration[5.1]
def change
add_reference :stars, :planetary_system, foreign_key: true
end
end
|
class Pnameforms::Piece10sController < ApplicationController
before_action :set_piece10, only: [:show, :edit, :update, :destroy]
# GET /piece10s
# GET /piece10s.json
def index
@pnameform = Pnameform.find(params[:pnameform_id])
@piece10s = @pnameform.piece10s
end
# GET /piece10s/10
# GET /piece10s/10.json
def show
@pnameform = Pnameform.find(params[:pnameform_id])
@piece10s = Piece10.all
end
# GET /piece10s/new
def new
@pnameform = Pnameform.find(params[:pnameform_id])
@piece10 = current_user.piece10s.build
end
# GET /piece10s/10/edit
def edit
@pnameform = Pnameform.find(params[:pnameform_id])
@piece10.pnameform = @pnameform
end
# POST /piece10s
# POST /piece10s.json
def create
@pnameform = Pnameform.find(params[:pnameform_id])
@piece10 = current_user.piece10s.build(piece10_params)
@piece10.pnameform = @pnameform
respond_to do |format|
if @piece10.save
format.html { redirect_to pnameform_piece10s_path(@pnameform), notice: 'Piece10 was successfully created.' }
format.json { render :show, status: :created, location: @piece10 }
else
format.html { render :new }
format.json { render json: @piece10.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /piece10s/10
# PATCH/PUT /piece10s/10.json
def update
@pnameform = Pnameform.find(params[:pnameform_id])
@piece10.pnameform = @pnameform
respond_to do |format|
if @piece10.update(piece10_params)
format.html { redirect_to pnameform_piece10s_path(@pnameform), notice: 'Piece10 was successfully updated.' }
format.json { render :show, status: :ok, location: @piece10 }
else
format.html { render :edit }
format.json { render json: @piece10.errors, status: :unprocessable_entity }
end
end
end
# DELETE /piece10s/10
# DELETE /piece10s/10.json
def destroy
@pnameform = Pnameform.find(params[:pnameform_id])
@piece10 = Piece10.find(params[:id])
title = @piece10.name
if @piece10.destroy
flash[:notice] = "\"#{title}\" was deleted successfully."
redirect_to pnameform_piece10s_path(@pnameform)
else
flash[:error] = "There was an error deleting."
render :show
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_piece10
@piece10 = Piece10.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def piece10_params
params.require(:piece10).permit(:name, :user_id)
end
end
|
class FeedSubscription < ActiveRecord::Base
belongs_to :feed
belongs_to :feed_item
end
|
require 'rltk/parser'
class FlechaParser < RLTK::Parser
left :OR
left :AND
right :NOT
left :EQ, :NE, :GE, :LE, :GT, :LT
left :PLUS, :MINUS
left :TIMES
left :DIV, :MOD
right :MINUS
class Environment < Environment
def generar_lambda(expresion, parametros)
parametros.reverse.inject(expresion) do |result, parametro|
['ExprLambda', parametro, result]
end
end
end
production(:programa) do
clause('') { [] }
clause('programa definicion') { |programa, definicion| programa + [definicion] }
end
production(:definicion) do
clause('DEF LOWERID DEFEQ expresion') do |_, lower_id, _, expresion|
['Def', lower_id, expresion]
end
clause('DEF LOWERID parametros DEFEQ expresion') do |_, lower_id, params, _, expresion|
['Def', lower_id, generar_lambda(expresion, params)]
end
end
production(:expresion) do
clause('expresion_externa') { |expr| expr }
clause('expresion_externa SEMICOLON expresion') do |expresion_externa, _, expresion|
['ExprLet', '_', expresion_externa, expresion]
end
end
production(:expresion_externa) do
clause('expresion_if') { |expr| expr }
clause('expresion_case') { |expr| expr }
clause('expresion_let') { |expr| expr }
clause('expresion_lambda') { |expr| expr }
clause('expresion_interna') { |expr| expr }
end
production(:expresion_if) do
clause('IF expresion_interna THEN expresion_interna ramas_else') do |_, condicion, _, bloque_then, ramas_else|
['ExprCase', condicion, [['CaseBranch', 'True', [], bloque_then], ramas_else]]
end
end
production(:ramas_else) do
clause('ELSE expresion_interna') { |_, expresion_interna| ['CaseBranch', 'False', [], expresion_interna] }
clause('ELIF expresion_interna THEN expresion_interna ramas_else') do |_, condicion, _, bloque_then, ramas_else|
['CaseBranch', 'False', [], ['ExprCase', condicion, [['CaseBranch', 'True', [], bloque_then], ramas_else]]]
end
end
production(:expresion_lambda) do
clause('LAMBDA parametros ARROW expresion_externa') do |_, parametros, _, expresion_externa|
generar_lambda(expresion_externa, parametros)
end
end
production(:parametros) do
clause('') { [] }
clause('LOWERID parametros') { |parametro, parametros| [parametro] + parametros }
end
production(:expresion_case) do
clause('CASE expresion_interna ramas_case') do |_, expresion_interna, ramas_case|
['ExprCase', expresion_interna, ramas_case]
end
end
production(:ramas_case) do
clause('') { [] }
clause('rama_case ramas_case') { |rama, ramas| [rama] + ramas }
end
production(:rama_case) do
clause('PIPE UPPERID parametros ARROW expresion_interna') do |_a, constructor, params, _, expresion_interna|
['CaseBranch', constructor, params, expresion_interna]
end
end
production(:expresion_interna) do
clause('expresion_aplicacion') { |expresion_aplicacion| expresion_aplicacion }
clause('expresion_interna operador_binario expresion_interna') do |expresion_interna_izquierda, operador_binario, expresion_interna_derecha|
['ExprApply', ['ExprApply', operador_binario, expresion_interna_izquierda], expresion_interna_derecha]
end
clause('operador_unario expresion_interna') do |operador_unario, expresion_interna|
['ExprApply', operador_unario, expresion_interna]
end
end
production(:expresion_let) do
clause('LET LOWERID DEFEQ expresion_interna IN expresion_externa') do |_, lower_id, _, expresion_interna, _, expresion_externa|
['ExprLet', lower_id, expresion_interna, expresion_externa]
end
clause('LET LOWERID parametros DEFEQ expresion_interna IN expresion_externa') do |_, lower_id, params, _, expresion_interna, _, expresion_externa|
['ExprLet', lower_id, generar_lambda(expresion_interna, params), expresion_externa]
end
end
production(:operador_binario) do
clause('AND') { |_| %w'ExprVar AND' }
clause('OR') { |_| %w'ExprVar OR' }
clause('EQ') { |_| %w'ExprVar EQ' }
clause('NE') { |_| %w'ExprVar NE' }
clause('GE') { |_| %w'ExprVar GE' }
clause('LE') { |_| %w'ExprVar LE' }
clause('GT') { |_| %w'ExprVar GT' }
clause('LT') { |_| %w'ExprVar LT' }
clause('PLUS') { |_| %w'ExprVar ADD' }
clause('MINUS') { |_| %w'ExprVar SUB' }
clause('TIMES') { |_| %w'ExprVar MUL' }
clause('DIV') { |_| %w'ExprVar DIV' }
clause('MOD') { |_| %w'ExprVar MOD' }
end
production(:operador_unario) do
clause('NOT') { |_| %w'ExprVar NOT' }
clause('MINUS') { |_| %w'ExprVar UMINUS' }
end
production(:expresion_atomica) do
clause('LOWERID') { |lower_id| ['ExprVar', lower_id] }
clause('UPPERID') { |upper_id| ['ExprConstructor', upper_id] }
clause('NUMBER') { |number| ['ExprNumber', number] }
clause('CHAR') { |character| ['ExprChar', character] }
clause('LPAREN expresion RPAREN') { |_, expresion, _| expresion }
clause('STRING') do |string|
string.split('').reverse.inject(%w(ExprConstructor Nil)) do |result, character|
['ExprApply', ['ExprApply', %w(ExprConstructor Cons), ['ExprChar', character.ord]], result]
end
end
end
production(:expresion_aplicacion) do
clause('expresion_atomica') { |expresion_atomica| expresion_atomica }
clause('expresion_aplicacion expresion_atomica') do |expresion_aplicacion, expresion_atomica|
['ExprApply', expresion_aplicacion, expresion_atomica]
end
end
finalize
end |
require File.expand_path(File.dirname(__FILE__) + '/../spec_helper')
describe UserSessionsController do
#Delete this example and add some real ones
it "should use SessionsController" do
controller.should be_an_instance_of(UserSessionsController)
end
describe "PUT 'destroy'" do
before(:each) do
@session = mock_model(UserSession, :destroy => nil)
UserSession.stub!(:find).and_return(@session)
end
it "should redirect to login_path" do
put 'destroy'
response.should redirect_to(login_path)
end
it "should destroy current user session" do
@session.should_receive(:destroy)
put 'destroy'
end
it "should assign logout message to flash[:error]" do
put 'destroy'
flash[:notice].should == I18n.t("messages.authentication.logged_out")
end
end
describe "GET new" do
context "when not logged in" do
it "should render new template" do
get :new
response.should render_template(:new)
end
it "should be successful" do
get :new
response.should be_success
end
it "should assign a new user session for the view" do
get :new
assigns[:user_session].new_record?.should be_true
end
end
context "when logged in" do
it "should redirect to admin page" do
@controller.stub!(:current_user).and_return(mock_model(User))
get 'new'
response.should redirect_to(admin_path)
end
end
end
describe "POST 'create'" do
before(:each) do
@user_session = mock_model(UserSession, :save => nil)
UserSession.stub!(:new).and_return(@user_session)
end
it "should pass params to new method" do
UserSession.should_receive(:new).with({'these' => 'params'})
post :create, :user_session => {'these' => 'params' }
end
it "should save user session" do
@user_session.should_receive(:save)
post :create
end
context "when user session saves successfully" do
before(:each) do
@user_session.stub!(:save).and_return(true)
post :create
end
it "should assign messages.authentication.login_successful to flash[:notice]" do
flash[:notice].should == I18n.t("messages.authentication.login_successful")
end
it "should redirect to admin_path" do
response.should redirect_to(admin_path)
end
end
context "when session fails to save" do
before(:each) do
@user_session.stub!(:save).and_return(false)
post :create
end
it "should redirect to login_path" do
response.should redirect_to(login_path)
end
it "should assign messages.authentication.login_failed to flash[:notice]" do
flash[:error].should == I18n.t("messages.authentication.login_failed")
end
end
end
end
|
# frozen_string_literal: true
require 'stannum/constraint'
require 'support/examples/constraint_examples'
RSpec.describe Stannum::Constraint do
include Spec::Support::Examples::ConstraintExamples
subject(:constraint) { described_class.new(**constructor_options) }
let(:constructor_options) { {} }
describe '.new' do
it 'should define the constructor' do
expect(described_class)
.to be_constructible
.with(0).arguments
.and_keywords(:negated_type, :type)
.and_any_keywords
.and_a_block
end
end
include_examples 'should implement the Constraint interface'
include_examples 'should implement the Constraint methods'
describe '#match' do
let(:match_method) { :match }
let(:expected_errors) { { type: constraint.type } }
let(:expected_messages) { expected_errors.merge(message: 'is invalid') }
describe 'with nil' do
let(:actual) { nil }
include_examples 'should not match the constraint'
end
describe 'with true' do
let(:actual) { true }
include_examples 'should not match the constraint'
end
describe 'with false' do
let(:actual) { false }
include_examples 'should not match the constraint'
end
describe 'with an integer' do
let(:actual) { 0 }
include_examples 'should not match the constraint'
end
describe 'with an Object' do
let(:actual) { Object.new.freeze }
include_examples 'should not match the constraint'
end
describe 'with an empty String' do
let(:actual) { '' }
include_examples 'should not match the constraint'
end
describe 'with a String' do
let(:actual) { 'a string' }
include_examples 'should not match the constraint'
end
describe 'with an empty Symbol' do
let(:actual) { :'' }
include_examples 'should not match the constraint'
end
describe 'with a Symbol' do
let(:actual) { :a_symbol }
include_examples 'should not match the constraint'
end
describe 'with an empty Array' do
let(:actual) { [] }
include_examples 'should not match the constraint'
end
describe 'with a Array' do
let(:actual) { %w[a b c] }
include_examples 'should not match the constraint'
end
describe 'with an empty Hash' do
let(:actual) { {} }
include_examples 'should not match the constraint'
end
describe 'with a Hash' do
let(:actual) { { a: 1, b: 2, c: 3 } }
include_examples 'should not match the constraint'
end
context 'when initialized with a block' do
subject(:constraint) do
described_class.new(**constructor_options, &constructor_block)
end
let(:constructor_block) { ->(actual) { actual.nil? } }
describe 'with an object that does not match the block' do
let(:actual) { Object.new.freeze }
include_examples 'should not match the constraint'
end
describe 'with an object that matches the block' do
let(:actual) { nil }
include_examples 'should match the constraint'
end
end
end
describe '#negated_match' do
let(:match_method) { :negated_match }
let(:expected_errors) { { type: constraint.negated_type } }
let(:expected_messages) { expected_errors.merge(message: 'is valid') }
describe 'with nil' do
let(:actual) { nil }
include_examples 'should match the constraint'
end
describe 'with true' do
let(:actual) { true }
include_examples 'should match the constraint'
end
describe 'with false' do
let(:actual) { false }
include_examples 'should match the constraint'
end
describe 'with an integer' do
let(:actual) { 0 }
include_examples 'should match the constraint'
end
describe 'with an Object' do
let(:actual) { Object.new.freeze }
include_examples 'should match the constraint'
end
describe 'with an empty String' do
let(:actual) { '' }
include_examples 'should match the constraint'
end
describe 'with a String' do
let(:actual) { 'a string' }
include_examples 'should match the constraint'
end
describe 'with an empty Symbol' do
let(:actual) { :'' }
include_examples 'should match the constraint'
end
describe 'with a Symbol' do
let(:actual) { :a_symbol }
include_examples 'should match the constraint'
end
describe 'with an empty Array' do
let(:actual) { [] }
include_examples 'should match the constraint'
end
describe 'with a Array' do
let(:actual) { %w[a b c] }
include_examples 'should match the constraint'
end
describe 'with an empty Hash' do
let(:actual) { {} }
include_examples 'should match the constraint'
end
describe 'with a Hash' do
let(:actual) { { a: 1, b: 2, c: 3 } }
include_examples 'should match the constraint'
end
context 'when initialized with a block' do
subject(:constraint) do
described_class.new(**constructor_options, &constructor_block)
end
let(:constructor_block) { ->(actual) { actual.nil? } }
describe 'with an object that does not match the block' do
let(:actual) { Object.new.freeze }
include_examples 'should match the constraint'
end
describe 'with an object that matches the block' do
let(:actual) { nil }
include_examples 'should not match the constraint'
end
end
end
end
|
class IspSession
extend Ispremote::Soap
operations :login, :logout
def initialize sid
self.sessionid = sid
end
def sessionid=(sid)
@sessionid = sid
end
def sessionid
@sessionid
end
def self.login
loginresponse = super(:message => {:username => Setting.remote_user, :password => Setting.remote_password })
IspSession.new loginresponse.hash[:envelope][:body][:login_response][:return]
end
def logout
@loginresponse = nil
r = super(:message => {:sessionid => @sessionid})
@sessionid = nil
r.hash[:envelope][:body][:logout_response][:return]
end
def valid?
!@sessionid.blank?
end
end
|
class Schedule < ApplicationRecord
belongs_to :service
belongs_to :customer
belongs_to :worker
end
|
When /^I create an index named (.*) on the (.*) collection$/ do |index_name, doc|
klass = doc.constantize
klass.index(index_name)
end
Then /^there is an index on (.*) on the (.*) collection$/ do |index_name, doc|
klass = doc.constantize
klass.collection.index_information.should include("#{index_name}_1")
end
|
class GameOfLife
attr_reader :initial_matrix, :next_matrix
def initialize(matrix)
@initial_matrix = matrix
@next_matrix = matrix
end
def check_top(x, y)
initial_matrix[x-1][y] == 1
end
def check_top_right(x, y)
initial_matrix[x - 1][y + 1] == 1
end
def check_right(x, y)
initial_matrix[x][y + 1] == 1
end
def check_bottom_right(x, y)
initial_matrix[x+1][y + 1] == 1
end
def check_bottom(x, y)
initial_matrix[x + 1][y] == 1
end
def check_bottom_left(x, y)
initial_matrix[x + 1][y - 1] == 1
end
def check_left(x, y)
initial_matrix[x][y - 1] == 1
end
def check_top_left(x, y)
initial_matrix[x - 1][y - 1] == 1
end
def check_num_alive(x, y)
[check_top(x,y), check_top_right(x, y), check_right(x, y),
check_bottom_right(x,y), check_bottom(x,y), check_bottom_left(x,y),
check_left(x, y), check_top_left(x, y)].count(true)
end
def check_num_dead(x, y)
8 - check_num_alive(x, y)
end
def determine_fate(x, y)
if initial_matrix[x][y] == 1 && check_num_alive(x, y) < 2
@next_matrix[x][y] = 0
elsif initial_matrix[x][y] == 1 && check_num_alive(x, y) <= 3
@next_matrix[x][y] = 1
elsif initial_matrix[x][y] == 1 && check_num_alive(x, y) > 3
@next_matrix[x][y] = 0
elsif initial_matrix[x][y] == 0 && check_num_alive(x, y) == 3
@next_matrix[x][y] = 1
end
end
end
|
class SlackersController < ApplicationController
def index
render json: { slackerboard: slackerboard.to_json }
end
private
def slackerboard
if this_week?
SlackerRanking.new(since: Time.zone.today.monday)
else
SlackerRanking.new
end
end
def this_week?
params.keys.include? 'thisweek'
end
end
|
require 'json'
require_relative './helpers/data_former_helper'
class ParserJson
include DataFormerHelper
def initialize(path, file_name)
@path = path
@file_name = file_name
end
def parse
data = JSON.parse(File.read(File.expand_path("#{@path}#{@file_name}.json", __FILE__)))
keys = []
values = []
data.each do |d|
d.each do |k, v|
keys << k
values << v
end
end
data_former(keys, values)
output_formatted_data
end
end
|
require 'spec_helper'
include Liquider
RSpec::Matchers.define :parse_to do |token_type|
match do |source|
string_scanner = StringScanner.new(source)
string_scanner.scan(token_type.pattern) && string_scanner.eos?
end
end
describe Tokens::IdentToken do
it 'cannot be empty' do
expect('').not_to parse_to(Tokens::IdentToken)
end
it 'can be composed of a single alphabetic character' do
['a', 'T', 'é', 'λ', 'Ж'].each do |s|
expect(s).to parse_to(Tokens::IdentToken)
end
end
it 'can be composed of a single underscore' do
expect('_').to parse_to(Tokens::IdentToken)
end
it 'cannot be composed of a digit or punctuation' do
['0', '9', '-', '!', '?'].each do |s|
expect(s).not_to parse_to(Tokens::IdentToken)
end
end
it 'cannot start with a digit or punctuation' do
['0foo', '9foo', '-foo', '!foo', '?foo'].each do |s|
expect(s).not_to parse_to(Tokens::IdentToken)
end
end
it 'can contain digits or hyphens' do
['a1234', 'a-b', 'a-1foo', '_1_-'].each do |s|
expect(s).to parse_to(Tokens::IdentToken)
end
end
it 'can end with a bang' do
['a!', '_!', 'a1!', 'a-!', 'a1a!'].each do |s|
expect(s).to parse_to(Tokens::IdentToken)
end
end
it 'can end with a question mark' do
['a?', '_?', 'a1?', 'a-?', 'a1a?'].each do |s|
expect(s).to parse_to(Tokens::IdentToken)
end
end
it 'cannot have a embedded bang' do
expect('a!a').not_to parse_to(Tokens::IdentToken)
end
it 'cannot have a embedded question mark' do
expect('a?a').not_to parse_to(Tokens::IdentToken)
end
end
|
require 'rails_helper'
RSpec.describe Order, type: :model do
describe "Associations" do
it "has many line_items" do
assc = described_class.reflect_on_association(:line_items)
expect(assc.macro).to eql :has_many
end
it "belongs to a user" do
assc = described_class.reflect_on_association(:user)
expect(assc.macro).to eql :belongs_to
end
it "has many products" do
assc = described_class.reflect_on_association(:products)
expect(assc.macro).to eql :has_many
end
it "has many promotions" do
assc = described_class.reflect_on_association(:promotions)
expect(assc.macro).to eql :has_many
end
end
end |
class CreateDragonhoards < ActiveRecord::Migration[5.2]
def change
create_table :dragonhoards do |t|
t.string :name
t.text :message
t.datetime :created_on
t.string :ogg
t.string :mp3
t.float :taxbase, limit: 53
t.float :taxinc, limit: 53
t.integer :ocpoints
t.integer :colorschemepoints
t.integer :colorschemecleanup
t.integer :treasury, default: 0
t.integer :contestpoints, default: 0
t.integer :conversioncost
t.integer :emeraldvalue
t.float :emeraldrate, limit: 53
t.integer :pointscreated
t.integer :profit, default: 0
t.boolean :denholiday, default: false
t.string :dragonimage
t.integer :blogadbannercost
t.integer :bloglargeimagecost
t.integer :blogsmallimagecost
t.integer :blogmusiccost
t.integer :blogpoints
t.integer :blogmascotpoints
t.integer :dreyterrium_start
t.integer :newdreyterriumcapacity
t.integer :dreyterrium_extracted, default: 0
t.integer :dreyterriumchange
t.integer :dreyterriumbasepoints
t.integer :dreyterriumcurrent_value
t.timestamps
end
end
end
|
class Followship < ApplicationRecord
validates :following_id, uniqueness: {scope: :user_id}
belongs_to :follower, class_name: :User, foreign_key: :user_id, counter_cache: :followings_count
belongs_to :following, class_name: :User, counter_cache: :followers_count
end
|
class CreateReservationStatuses < ActiveRecord::Migration[5.0]
def change
create_table :reservation_statuses do |t|
t.string :type
t.timestamps
end
add_column :reservations, :reservation_status_id, :integer
end
end
|
class User < ActiveRecord::Base
has_many :user
has_many :authentications
has_many :trails
has_one :setting
has_many :pages
# Include default devise modules. Others available are:
# :token_authenticatable, :confirmable, :lockable and :timeoutable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
# Setup accessible (or protected) attributes for your model
attr_accessible :email, :password, :password_confirmation, :remember_me
def current_trail
trails.find(setting.current_trail_id)
end
def sorted_trails
trails.order("column_id, sort_index")
end
# This shouldn't be necessary.
def feeds
Feed.where(:user_id=>id).order("sort_order asc")
# Feed.order("order asc")
end
def apply_omniauth(omniauth)
self.email = omniauth['user_info']['email'] if email.blank?
authentications.build(:provider => omniauth['provider'], :uid => omniauth['uid'])
end
def password_required?
(authentications.empty? || !password.blank?) && super
end
end
|
class Admins::BannersController < ApplicationController
before_action :authenticate_admin!
def index
@banners = Banner.where(status: 1).order('sort_order IS NULL').order(sort_order: 'ASC', id: 'ASC')
end
def new
@banner = Banner.new()
end
def create
@banner = Banner.new(banner_params)
if @banner.save() #save data
redirect_to admins_banners_path
else
render 'new' #if failed render new to disply errror
end
end
def edit
@banner = Banner.find(params[:id])
end
def update
@banner = Banner.find(params[:id])
if @banner.update(banner_params) #save data
redirect_to admins_banners_path
else
render 'edit' #if failed render new to disply errror
end
end
def destroy
@banner = Banner.find(params[:id])
if(@banner.update(:status => 0))
redirect_to admins_banners_path
else
redirect_to admins_banners_path
end
end
private
def banner_params
params.require(:banner).permit(:title, :url, :use_url, :article_id, :category_id, :image_banner, :image_alt, :sort_order).merge(status: 1)
end
end
|
require "./cellnum.rb"
require "./assembler.rb"
class Disassembler
def Disassembler.disassemble(code)
cmd,param1,param2=code
return ("#{cmd} "+Disassembler.disassemble_param(param1)+" "+Disassembler.disassemble_param(param2)).strip
end
def Disassembler.disassemble_param(param)
return "" if not param
type,val,op = param
str_type = case type
when :indirect then "**"
when :direct then "*"
else ""
end
str_op = case op
when :inc then "+"
when :dec then "-"
else ""
end
return str_type + "#{val}"+str_op
end
def Disassembler.bin_to_code(bin)
raise "Dissambler failed at bin_to_code invalid data: #{bin}" if not
bin=~/([01]{2})([01])([01]{16})([01]{2})([01]{2})([01])([01]{16})([01]{2})([01]{6})/
param1=$~[1..4]
param2=$~[5..8]
cmd=$~[9]
code = [Disassembler.bin_to_cmd(cmd),Disassembler.bin_to_param(param1),Disassembler.bin_to_param(param2)]
raise "Dissasembler failed because of unexpected nonempty second param"if code[1]==nil && code[2]!=nil
return code
end
def Disassembler.bin_to_cmd(bin)
index=bin.to_i(2)
if (0...Assembler.cmds.length)===index then
return Assembler.cmds[index]
else
raise "Disassembling failed at bin_to_cmd invalid data: #{bin}"
end
end
def Disassembler.bin_to_param(param)
bin_type,bin_val_type,bin_val,bin_op=param
return nil if ["00","0","0"*16,"00"]==param
type = case bin_type
when "00" then raise "Disassembly failed: unknown bin_type 00"
when "01" then :direct
when "10" then :indirect
when "11" then :immediate
end
if bin_val_type == "1" then
if (0...Assembler.regs.length)===bin_val.to_i(2) then
val = Assembler.regs[bin_val.to_i(2)]
else raise "Disassembler failed at bin_val_type: invalid register #{bin_val.to_i(2)}"
Assembler.regs[bin_val.to_i(2)]
end
elsif bin_val_type == "0" then
val = Cellnum.from_16_bit(bin_val)
else
raise "Disassembler is really angry! srsly this should never happen"
end
op = case bin_op
when "00" then raise "Disassembly failed: unknown bin_op 00"
when "01" then :inc
when "10" then :dec
when "11" then nil
end
return type,val,op
end
end
|
class AddEnergyToClothes < ActiveRecord::Migration[6.1]
def change
add_column :clothes, :energy_consumption, :string
end
end
|
class PostSerializer < ActiveModel::Serializer
attributes :id, :title, :content, :created_at, :url_for_post, :associated_topics
has_many :post_links
end
|
require 'securerandom'
require 'spec_helper'
describe "Binding a Riak CS service instance" do
let(:instance_id) { SecureRandom.uuid }
let(:binding_id) { SecureRandom.uuid }
def make_request(id = instance_id, b_id = binding_id)
put "/v2/service_instances/#{id}/service_bindings/#{b_id}"
end
it "returns an Unauthorized HTTP response" do
make_request
expect(last_response.status).to eq(401)
end
context "when authenticated", :authenticated do
context "when the service instance exists" do
before do
create_instance
end
context "when it is not bound" do
context "when binding is successful" do
it "returns a 201 Created HTTP response" do
make_request
expect(last_response.status).to eq(201)
end
it "returns a JSON object containing credentials" do
make_request
expect(last_response.body).to have_json_path('credentials/uri')
expect(last_response.body).to have_json_path('credentials/access_key_id')
expect(last_response.body).to have_json_path('credentials/secret_access_key')
end
end
context "when binding is unsuccessful because the service is unavailable" do
before do
expect_any_instance_of(RiakCsBroker::ServiceInstances).to receive(:bind).and_raise(RiakCsBroker::ServiceInstances::ServiceUnavailableError)
end
it "returns 503 Service Not Available with an error message" do
make_request
expect(last_response.status).to eq(503)
expect(last_response.body).to be_json_eql({ description: "Could not bind because service is unavailable" }.to_json)
end
end
end
context "when it is already bound" do
before do
expect_any_instance_of(RiakCsBroker::ServiceInstances).to receive(:bound?).and_return(true)
end
it "returns a 409 Conflict HTTP response with an empty JSON" do
make_request
expect(last_response.status).to eq(409)
expect(last_response.body).to be_json_eql("{}")
end
end
context "when there are errors when accessing Riak CS" do
before do
allow_any_instance_of(RiakCsBroker::ServiceInstances).to receive(:bind).and_raise(RiakCsBroker::ServiceInstances::ClientError.new("some-error-message"))
end
it_behaves_like "an endpoint that handles errors when accessing Riak CS"
end
end
context "when the service instance does not exist" do
it "returns 404 Not Found with an error message" do
make_request
expect(last_response.status).to eq(404)
expect(last_response.body).to be_json_eql({ description: "Could not bind to an unknown service instance: #{instance_id}" }.to_json)
end
end
end
end
describe "Unbinding a Riak CS service instance" do
let(:instance_id) { SecureRandom.uuid }
let(:binding_id) { SecureRandom.uuid }
def make_request(id = instance_id, b_id = binding_id)
delete "/v2/service_instances/#{id}/service_bindings/#{b_id}"
end
it "returns an Unauthorized HTTP response" do
make_request
expect(last_response.status).to eq(401)
end
context "when authenticated", :authenticated do
context "when the service instance exists" do
before do
create_instance
end
context "when it is not bound" do
before do
allow_any_instance_of(RiakCsBroker::ServiceInstances).to receive(:unbind).and_raise(RiakCsBroker::ServiceInstances::BindingNotFoundError)
end
it "returns 410 Not Found with an empty JSON" do
make_request
expect(last_response.status).to eq(410)
expect(last_response.body).to be_json_eql('{}')
end
end
context "when it is bound" do
before do
expect_any_instance_of(RiakCsBroker::ServiceInstances).to receive(:unbind)
end
it "returns 200 OK with with an empty JSON" do
make_request
expect(last_response.status).to eq(200)
expect(last_response.body).to be_json_eql('{}')
end
context "when binding is unsuccessful because the service is unavailable" do
before do
allow_any_instance_of(RiakCsBroker::ServiceInstances).to receive(:unbind).and_raise(RiakCsBroker::ServiceInstances::ServiceUnavailableError)
end
it "returns 503 Service Not Available with an error message" do
make_request
expect(last_response.status).to eq(503)
expect(last_response.body).to be_json_eql({ description: "Could not bind because service is unavailable" }.to_json)
end
end
context "when there are errors when accessing Riak CS" do
before do
allow_any_instance_of(RiakCsBroker::ServiceInstances).to receive(:unbind).and_raise(RiakCsBroker::ServiceInstances::ClientError.new("some-error-message"))
end
it_behaves_like "an endpoint that handles errors when accessing Riak CS"
end
end
end
context "when the service instance does not exist" do
it "returns 410 Not Found with an empty JSON" do
make_request
expect(last_response.status).to eq(410)
expect(last_response.body).to be_json_eql('{}')
end
end
end
end
|
class ShopsController < ApplicationController
def index
@categories = Category.all
@shops = Shop.search(params[:search])
end
def show
@shop = Shop.find(params[:id])
@review_access = @shop.reviews.find_by(:user_id => current_user.id) if user_signed_in?
end
def edit
if user_signed_in?
@shop = Shop.find(params[:id])
else
redirect_to root_path
end
end
def new
if user_signed_in?
@shop = Shop.new
else
redirect_to root_path
end
end
def create
if user_signed_in?
@shop = Shop.new(shop_params)
if @shop.save
flash[:success] = "Shop created"
redirect_to root_path
else
flash[:error] = "Error : Invalid Shop title"
render "new"
end
else
redirect_to root_path
end
end
def update
if current_user == @user or current_user.admin?
@shop = Shop.find(params[:id])
if @shop.update(shop_params)
redirect_to @shop
else
render 'edit'
end
else
redirect_to root_path
end
end
def destroy
@user = User.find(params[:id])
if current_user == @user or current_user.admin?
Shop.destroy(params[:id])
redirect_to root_path
else
redirect_to root_path
end
end
private
def shop_params
params.require(:shop).permit(:title, :image, :user_id, :category_id, :review_id)
end
end
|
require File.dirname(__FILE__) + '/../test_helper'
class HostTest < Test::Unit::TestCase
def setup
Host.delete_all
end
def test_creation
assert_equal 0, Host.count
assert_nothing_raised{
h = Host.create!(:name => "test.example.com")
}
assert_equal 1, Host.count
end
def test_validation
h = Host.create!(:name => "192.168.0.1")
# try to create another host with the same name
h = Host.new(:name => "192.168.0.1")
assert !h.valid?
assert_not_nil h.errors.on("name")
# try to create a host with a name that is too long
name = "com." * 251
name = name.chop
h = Host.new(:name => name)
assert !h.valid?
assert_not_nil h.errors.on("name")
# make it pass
name = "example.com"
h = Host.new(:name => name)
assert h.valid?
end
def test_validation_of_name_if_ip
# some valid IPs
assert valid_host_name('192.168.0.1 ')
assert valid_host_name(' 192.168.0.110')
# some invalid IPs
assert invalid_host_name('192.168.0.1100')
assert invalid_host_name(' 192.168.100')
assert invalid_host_name('999.168.0.110')
end
def test_validation_of_name_if_domain_name
# some valid domain names
assert valid_host_name('map.example.com')
assert valid_host_name('www12.example.com')
assert valid_host_name('localhost')
# some invalid domains
assert invalid_host_name('_aa.example.com')
assert invalid_host_name('mail:example.com')
assert invalid_host_name('mail*.#.example.com')
end
def test_stages
host = create_new_host
stage_1 = create_new_stage
role_1 = create_new_role(:name => 'www', :stage => stage_1, :host => host)
role_2 = create_new_role(:name => 'app', :stage => stage_1, :host => host)
stage_2 = create_new_stage
role_3 = create_new_role(:name => 'www', :stage => stage_2, :host => host)
role_4 = create_new_role(:name => 'app', :stage => stage_2, :host => host)
assert_equal 4, host.roles.count
assert_equal 2, host.stages.uniq.size # XXX pure count does not work!!!
assert_equal [stage_1.id, stage_2.id].sort, host.stages.collect(&:id).sort
assert_equal [host], stage_1.hosts
assert_equal [host], stage_2.hosts
end
# helper functions
def valid_host_name(name)
h = Host.new
h.name = name
h.valid?
end
def invalid_host_name(name)
!valid_host_name(name)
end
end
|
=begin
Copyright (c) 2013 ExactTarget, Inc.
All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this list of conditions and the
following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the
following disclaimer in the documentation and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote
products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
=end
module FuelSDK
VERSION = "0.0.5"
end
|
ActiveAdmin.application.tap do |config|
# Set the default configuration for authenticating with admin users
config.authentication_method = :authenticate_admin_user!
config.current_user_method = :current_admin_user
config.logout_link_method = :delete
config.logout_link_path = :destroy_admin_user_session_path
# Prefer short date and time format
config.localize_format = :short
# Add the meta tags to enable Active Admin as an iOS home screen app
config.meta_tags ||= {}
config.meta_tags["apple-mobile-web-app-capable"] ||= "yes"
config.meta_tags["apple-mobile-web-app-title"] ||= "Admin"
config.meta_tags["viewport"] ||= "initial-scale=1, maximum-scale=1, width=device-width"
# Add route and controller for Summernote's image uploads
config.load_paths.unshift File.join(File.expand_path("../../..", __FILE__), "lib", "active_admin_pro", "summernote_image")
end
|
class DeleteWinFromMatches < ActiveRecord::Migration
def self.up
remove_column(:matches, :win)
end
def self.down
add_column(:matches, :win, :boolean)
end
end
|
module Opity
module Resource
class Balancer < Base
attribute :name
attribute :type
attribute :environment
attribute :application
def list
[self, Opity::Resource::Dns.new(name: self.name, type: 'dns')]
end
def valid?
b = self.class.balancers.detect {|e| e.id == name}
return false if b.nil?
true
end
class << self
def balancers
@balancers ||= begin
x = Opity.connect.balancer
x.load_balancers
end
end
end
end
end
end |
class ChangeDocumentsPagesToContent < ActiveRecord::Migration
def change
rename_column :documents, :pages, :content
end
end
|
FactoryGirl.define do
factory :partner do
name_ru { generate :string }
description_ru { generate :string }
end
end
|
require_relative "../ebook_converter"
require_relative "../prince"
require_relative "../preprocessor"
require_relative "../postprocessor"
require_relative "../prince_post_processor"
require 'yaml'
require 'zip'
## x = FileList["text/**/*.md"]
## x.pathmap("new file pattern %n %x") %p %f %d %x %n {^source,target}
# directory "newdir"
# file "target file" => [source files] do
# sh
# end
# TARGET_FILES.zip(SOURCE_FILES).each do |target, source|
# file target => ["newdir", source]
# file "final.png" => TARGET_FILES
# task convert => "final.png"
namespace :pub_rx do
TYPES = %w(pdf epub mobi)
task :load do
$settings = YAML.load_file("settings.yml")
end
task :clean do
`rm -rf output/preprocessed`
`rm -rf output/postprocessed`
`rm -rf output/converted`
`rm output/*.zip`
`rm -rf output/images`
`mkdir output/preprocessed`
`mkdir output/postprocessed`
`mkdir output/converted`
`mkdir output/images`
TYPES.each do |type|
`rm output/*.#{type}`
end
end
desc "copy images"
task :image_copy => [:clean] do
`cp images/*.png output/images`
end
task :preprocess => [:load, :clean, :image_copy] do
Preprocessor.process_directory("text/**/*.md")
end
task :markdownify => :preprocess do
Dir["output/preprocessed/*.md"].sort.each do |path|
file_name = path.split("/")[-1]
`multimarkdown #{path} > output/converted/#{file_name}.html`
end
end
task :sass do
`sass layout/styles.scss output/styles.css`
end
task :postprocess => :markdownify do
Dir["output/converted/*.html"].sort.each do |path|
file_name = path.split("/")[-1]
text = File.new(path).read
marker = file_name.split("_").select { |segment| segment.match(/\d+/) }.join("_")
text = Postprocessor.new(text, marker).process
File.open("output/postprocessed/#{file_name}", 'w') do |f|
f << text
end
end
end
task :make_page => :postprocess do
text = ""
Dir["output/postprocessed/*.html"].sort.each do |path|
text << File.new(path).read
end
html_template = File.new("layout/template.html").read
html_template.gsub!("#body", text)
File.open('output/index.html', 'w') do |f|
f.puts html_template
end
end
task :build => [:sass, :make_page]
task :prince_post_process => :build do
text = File.new("output/index.html").read
text = PrincePostProcessor.new(text).process
File.open('output/prince_index.html', 'w') do |f|
f << text
end
end
task :prince => :prince_post_process do
princely = Prince.new
princely.add_style_sheets("output/styles.css", "layout/code_ray.css")
html_string = File.new('output/prince_index.html').read
File.open("output/#{$settings["filename"]}.pdf", 'w') do |f|
f.puts princely.pdf_from_string(html_string)
end
end
task :pdf => :build do
PdfConverter.new("output/index.html").convert
end
task :epub => :build do
EpubConverter.new("output/index.html").convert
end
task :mobi => :build do
MobiConverter.new("output/index.html").convert
end
task :ebooks => [:prince, :epub, :mobi, :zip]
task :zip do
zipfile = "output/#{$settings["filename"]}_#{$settings["version"]}.zip"
Zip::File.open(zipfile, Zip::File::CREATE) do |zipfile|
TYPES.each do |type|
zipfile.add("#{$settings["filename"]}.#{type}",
"output/#{$settings["filename"]}.#{type}")
end
end
end
end
|
class AddPhotoToBusinesses < ActiveRecord::Migration
def change
add_attachment :businesses, :logo
end
end
|
module Jruby::Pcap
class Frame
def initialize(handle, frame)
@handle = handle
@frame = frame
@header = @frame.header
end
def src_addr
@header.src_addr.to_s.gsub("/","")
end
def src_host
@header.src_addr.host_name
end
def src_port
@header.src_port.value_as_string
end
def src_port_name
@header.src_port.name
end
def dst_addr
@header.dst_addr.to_s.gsub("/","")
end
def dst_host
@header.dst_addr.host_name
end
def dst_port
@header.dst_port.value_as_string
end
def dst_port_name
@header.dst_port.name
end
def protocol
@header.protocol.name
end
def version
@header.version.name
end
def length
@frame.length
end
def to_hash
hash = {}
if (@frame.is_a?(IpV4Packet))
hash['src_addr'] = src_addr
hash['dst_addr'] = dst_addr
hash['procotol'] = protocol
hash['version'] = version
hash['ip_length'] = length
elsif (@frame.is_a?(TcpPacket) || @frame.is_a?(UdpPacket))
hash['src_port'] = src_port
hash['src_port_name'] = src_port_name
hash['dst_port'] = dst_port
hash['dst_port_name'] = dst_port_name
hash['tcpip_length'] = length
end
hash
end
end
end
|
#encoding: utf-8
class SpecimenGroupRelationship < ActiveRecord::Base
# Constants
# Put here constants for SpecimenGroupRelationship
# Relations
belongs_to :specimen
belongs_to :specimen_group
# Callbacks
# Put here custom callback methods for SpecimenGroupRelationship
# Validations
# validates :specimen, <validations>
# validates :specimen_group, <validations>
# Scopes (used for search form)
# Put here custom queries for SpecimenGroupRelationship
scope :by_name, ->(name) { where("name ILIKE ?", "%#{name}%") } # Scope for search
# Instance methods
# Override to_s method
def to_s
(defined? name)? name : ((defined? email)? email : id) # editable
end
end
|
class EnquiryService < ApplicationRecord
belongs_to :service
belongs_to :enquiry
validates :service_id, uniqueness: { scope: :enquiry_id }
end
|
module Rockauth
class SessionsController < ActionController::Base
include Rockauth::Controllers::Scope
include Rockauth::Controllers::UnsafeParameters
before_filter :set_variables
helper_method :resource
helper_method :param_key
helper_method :resource_owner_class
layout :configured_layout
def new
build_resource
if warden.user(@scope).present?
redirect_to (consume_sign_in_uri || scope_settings[:after_sign_in_url]), flash: { notice: I18n.t("rockauth.sessions.existing_session") }
end
end
def create
env['warden'].logout(@scope) # assume that someone attempting to post to login wants to login again, and log them out
warden.authenticate scope: @scope
if warden.user(@scope).present?
redirect_to consume_sign_in_uri || scope_settings[:after_sign_in_url], flash: { notice: I18n.t("rockauth.sessions.created") }
else
build_resource
render :new, flash: { error: I18n.t("rockauth.sessions.creation_failed") }
end
end
def destroy
env['warden'].user(@scope).try(Rockauth::Configuration.signout_method)
env['warden'].logout(@scope)
redirect_to scope_settings[:after_sign_out_url], flash: { notice: I18n.t("rockauth.sessions.destroyed") }
end
def failure
if params[:controller].split('/').last == 'sessions' && %w{new create}.include?(params['action'])
build_resource
render :new, flash: { error: I18n.t("rockauth.sessions.required") }
else
redirect_to [:new, @scope, :session]
end
end
def resource_owner_class
@resource_owner_class ||= (params[:resource_owner_class_name] || env['warden.options'][:scope].to_s.camelize).safe_constantize
end
protected
def configured_layout
(Rockauth::Configuration.session_layout || -> (*_) { 'application' }).call(@scope)
end
def warden
env['warden']
end
def set_variables
@authentication_class = Rockauth::Configuration.authentication_class
@scope = resource_owner_class.model_name.param_key
end
def resource
@authentication
end
def build_resource
@authentication = @authentication_class.new permitted_params[param_key]
end
def permitted_params
params.permit(param_key => [:username, :password, :token])
end
def param_key
:authentication
end
def consume_sign_in_uri
value = session[:"#{@scope}_sign_in_return_uri"]
session[:"#{@scope}_sign_in_return_uri"] = nil
value
end
end
end
|
require "rails_helper"
RSpec.feature "Visitor adds a space to cart" do
context "valid reservation" do
scenario "visitor adds a valid reservation to the cart" do
space = create(:space, approved: true)
visit space_path(space)
fill_in "start_date", with: "2016/08/17"
fill_in "end_date", with: "2016/08/19"
click_on "Reserve this Space"
click_on "Cart"
expect(current_path).to eq("/cart")
within '#cart-spaces' do
expect(page).to have_css("img[src=\"#{space.image_url.url(:thumb)}\"]")
expect(page).to have_content(space.name)
expect(page).to have_content(space.price)
expect(page).to have_content(space.planet.name)
expect(page).to have_content(space.style.name)
expect(page).to have_content("August 17, 2016")
expect(page).to have_content("August 19, 2016")
end
within '#total-cart-price' do
expect(page).to have_content("Cart Total: $#{space.price * 2}")
expect(page).to have_content("Total Spaces: 1")
end
end
end
context "invalid reservation" do
scenario "visitor adds a valid reservation to the cart" do
space = create(:space, approved: true)
create(:reservation, space: space)
visit space_path(space)
fill_in "start_date", with: "2016/07/14"
fill_in "end_date", with: "2016/07/16"
click_on "Reserve this Space"
expect(current_path).to eq(space_path(space))
expect(page).to have_content("Your current date range is not available.")
end
end
end
|
require 'spec_helper'
require 'timecop'
require_relative 'shared_examples'
RSpec.describe Bambooing::Timesheet::Clock::Entry::Factory do
let(:employee_id) { 'an_employee_id' }
let(:pto_class) { Bambooing::TimeOff::Table::PTO }
describe '.create_current_weekdays' do
let(:method) { :create_current_weekdays }
it_behaves_like 'entry collection'
it '40 hours are worked' do
entries = described_class.create_current_weekdays(employee_id: employee_id)
elapsed_seconds = seconds_worked_for(entries)
expect(elapsed_seconds).to eq(40*60*60)
end
context 'when exclude_time_off is enabled' do
let(:requests) do
[pto_class.new(start: Date.new(2019,7,22), end: Date.new(2019,7,23))]
end
before do
Timecop.freeze(Date.new(2019,7,22))
allow(pto_class).to receive(:approved).and_return(requests)
end
it '24 hours are worked' do
entries = described_class.create_current_weekdays(employee_id: employee_id, exclude_time_off: true)
elapsed_seconds = seconds_worked_for(entries)
expect(elapsed_seconds).to eq(24*60*60)
end
after do
Timecop.return
end
end
end
describe '.create_current_month_weekdays' do
let(:method) { :create_current_month_weekdays }
it_behaves_like 'entry collection'
it '176 hours are worked' do
Timecop.freeze(Date.new(2019,8,30))
entries = described_class.create_current_month_weekdays(employee_id: employee_id)
elapsed_seconds = seconds_worked_for(entries)
expect(elapsed_seconds).to eq(176*60*60)
Timecop.return
end
context 'when exclude_time_off is enabled' do
let(:requests) do
[pto_class.new(start: Date.new(2019,8,1), end: Date.new(2019,8,2))]
end
before do
Timecop.freeze(Date.new(2019,8,30))
allow(pto_class).to receive(:approved).and_return(requests)
end
it '160 hours are worked' do
entries = described_class.create_current_month_weekdays(employee_id: employee_id, exclude_time_off: true)
elapsed_seconds = seconds_worked_for(entries)
expect(elapsed_seconds).to eq(160*60*60)
end
after do
Timecop.return
end
end
end
def seconds_worked_for(entries)
entries.reduce(0) do |acc, entry|
acc += entry.end.to_i - entry.start.to_i
end
end
end
|
require 'httparty'
require 'active_collab/version'
require 'active_collab/client'
module ActiveCollab
@@api_key = nil
@@api_url = nil
def self.api_key=(api_key)
@@api_key = api_key
end
def self.api_url=(api_url)
@@api_url = api_url
end
def self.client
ActiveCollab::Client.new(@@api_url, @@api_key)
end
end
|
class ReviewTag < AbstractTag
belongs_to :review
belongs_to :tag, :class_name => 'NormalizedTag', :foreign_key => 'normalized_tag_id'
acts_as_list :scope => 'review_id = #{review_id} AND kind = \'#{kind}\'', :column => :sort_order
validates_uniqueness_of :value, :scope => [:review_id, :kind], :allow_nil => false
def initialize(attributes = nil)
super
attributes ||= {}
self.value ||= ""
end
def after_save
delete and return unless review
unless @in_after_save
EndecaEvent.fire! self.review, :replace if self.review.status == :active
@in_after_save = true
# note that tags.value is unique, so no new record will be inserted if it already exists
t = NormalizedTag.find_or_create value
self.update_attribute :tag, t
@in_after_save = false
end
end
def after_destroy
EndecaEvent.fire! self.review, :replace if self.review.status == :active
end
def self.most_popular_about_me(limit=25,excludes=[],months_back=1)
sql = <<-SQL
SELECT sub.*, COUNT(distinct user_id) AS cnt FROM (
SELECT DISTINCT rt.*, r.user_id
FROM review_tags rt
INNER JOIN reviews r FORCE INDEX (reviews_published_at_index) ON r.id = rt.review_id
AND (r.status = 'active' OR r.status = 'draft')
AND r.published_at > (CURRENT_DATE - INTERVAL #{months_back} MONTH)
LEFT OUTER JOIN blacklisted_tags bt ON bt.kind = 'about_me' AND bt.value = rt.value
WHERE rt.kind = 'about_me'
AND bt.value IS NULL
SQL
values = []
if excludes
excludes.each do |e|
sql << " AND rt.value <> ? "
values << e
end
end
sql << ' ) AS sub'
sql << ' GROUP BY value ORDER BY cnt DESC'
sql << ' LIMIT ?'
values << limit
ReviewTag.find_by_sql [sql, *values]
end
end
|
require 'active_support/all' # Should be required first.
require 'seed_migrator/update_class_loader' #Should be required second.
require 'seed_migrator/updater'
require 'seed_migrator/seeds'
# Extends the migrations DSL to include the functionality to execute data updates.
#
# Note that each data update class is instantiated regardless of whether it is
# expected to run. This enables the developer to discover any data update that
# is incorrectly referenced in a migration, prior to deployment to production.
module SeedMigrator
include SeedMigrator::UpdateClassLoader
# Returns the root data updates path.
def root_updates_path
raise "Must override in subclass!"
end
# Return +true+ if the named update should run, +false+ otherwise. Subclasses
# are expected to override this as needed.
def should_run?(update_name)
true
end
# Applies the given update.
# @param [String|Symbol] update_name
def apply_update(update_name)
perform(update_name, :perform_update)
end
# Reverts the given update.
# @param [String|Symbol] update_name
def revert_update(update_name)
perform(update_name, :undo_update)
end
# Perform the update action.
# @param [String] update_name
# @param [Symbol] action Update action.
# Either :perform_update or :undo_update
def perform(update_name, action)
update = load_updater_class(update_name)
update.send(action) if should_run?(update_name)
end
private :perform
# Load the updater class and instantiate it. This enables the developer
# to discover when the data update has been incorrectly referenced in the
# migration, prior to deployment to production.
# @param [String] update_name
def load_updater_class(update_name)
get_update_class(root_updates_path, update_name).new
end
private :load_updater_class
end
|
#encoding: UTF-8
class CoverPhoto
include Mongoid::Document
include Mongoid::Paperclip
include Mongoid::Timestamps
# extend Mongoid::PaperclipQueue
store_in collection: "cover_photo", database: "dishgo"
field :original_url, type: String
field :position, type: Integer
field :img_url_medium, type: String
field :img_url_original, type: String
field :height, type: Integer
field :width, type: Integer
belongs_to :restaurant, class_name: "Restaurant", inverse_of: :cover_photos, index: true
index({ _id:1 }, { unique: true, name:"id_index" })
has_mongoid_attached_file :img, {
:path => ':hash_:style.png',
:hash_secret => "we_like_food",
:styles => {
:original => { res_ize: '1920x999999999>' },
:medium => { res_ize: '420x999999999>' },
},
:processors => [:converter, :compressor],
storage: :fog,
fog_credentials: {
provider: 'Rackspace',
rackspace_username: 'ptolts',
rackspace_api_key: RACKSPACE_KEY,
rackspace_region: :iad,
persistent: false
},
fog_directory: 'cover_photos',
fog_public: true,
}
field :img_fingerprint, type: String
field :manual_img_fingerprint, type: String
validates_attachment_content_type :img, :content_type => %w(image/jpeg image/jpg image/png), :message => 'file type is not allowed (only jpeg/png/gif images)'
after_post_process :img_post_process
before_post_process :fuck_you_paperclip
default_scope -> {desc(:created_at)}
def self.set_default_scope opts
self.default_scoping = nil
eval("default_scope -> #{opts}")
end
def fuck_you_paperclip
if @background_process
return true
else
return false
end
end
def do_background_work
@background_process = true
img.reprocess!
end
def img_url_medium
return super.to_s.gsub(/http:\/\//,'https://').gsub(/\.r.{2}\./,'.ssl.')
end
def img_url_original
return super.to_s.gsub(/http:\/\//,'https://').gsub(/\.r.{2}\./,'.ssl.')
end
def custom_to_hash
return {_id: _id, id: _id, local_file: self.img_url_medium, medium: self.img_url_medium, rejected: false, original: self.img_url_original}
end
def serializable_hash options
options ||= {}
start = super {}
start[:id] = self._id
start[:_id] = self._id
start[:medium] = self.img_url_medium
start[:original] = self.img_url_original
start
end
def img_post_process
self.img_url_medium = img.url(:medium)
self.img_url_original = img.url(:original)
tempfile = img.queued_for_write[:original]
unless tempfile.nil?
geometry = Paperclip::Geometry.from_file(tempfile)
self.manual_img_fingerprint = Digest::MD5.hexdigest(File.open(tempfile.path).read)
self.width = geometry.width.to_i
self.height = geometry.height.to_i
self.img_file_size = tempfile.size
end
end
end
|
Vertex = Struct.new(:graph, :label) do
def initialize(graph, label)
self.explored = false
super(graph, label)
end
attr_writer :explored
def explored?
@explored
end
def unexplored?
!explored?
end
def outgoing_edges
@outgoing_edges ||= []
end
def incoming_edges
@incoming_edges ||= []
end
def to_s
"#<V #{label}>"
end
alias inspect to_s
end
Edge = Struct.new(:tail, :head) do
def initialize(tail, head)
super
tail.outgoing_edges << self
head.incoming_edges << self
end
def to_s
"<E #{tail.label} => #{head.label}>"
end
alias inspect to_s
end
class Graph
def initialize
@vertices = Hash.new do |hash, label|
hash[label] = Vertex.new(self, label)
end
@num_edges = 0
if block_given?
yield self
@vertices = @vertices.values # otherwise we can't Marshal.dump it...
end
end
def add_edge(tail, head)
tail_v = @vertices[tail]
head_v = @vertices[head]
@num_edges += 1
edges << Edge.new(tail_v, head_v)
if @num_edges % 50000 == 0
puts "Added #{@num_edges} edges so far...."
end
end
def edges
@edges ||= Array.new(5000000)
end
def vertices
return @vertices unless @vertices.respond_to?(:values)
@vertices.values
end
def self.from_file(file)
new do |g|
File.open(file, 'r') do |f|
lines = f.lines
lines = yield(lines) if block_given?
lines.each do |line|
g.add_edge(*line.split(/\s+/).map(&:to_i))
end
end
end
end
end
|
class TemporaryUser < ApplicationRecord
def voted_on?(object, positive)
object_type = object.class.to_s.downcase
return positive == true if (public_send("parsed_#{object_type}s") || {})[object.id.to_s].present?
vote_id = parsed_votes[object_type][object.id.to_s]
return false if vote_id.nil?
vote = object.public_send("#{object_type}_votes").find(vote_id)
positive == vote.try(:trust) > 0
end
def has_flagged?(object)
flag_id_for(object).present?
end
def flag_id_for(object)
parsed_flags[object.class.to_s.downcase][object.id.to_s]
end
def flag_for(object)
Flag.find(flag_id_for(object))
end
def self.add_object(object, remote_ip)
temporary_user = TemporaryUser.find_or_create_by(ip_address: remote_ip)
if object.class.to_s =~ /Vote/
temporary_user.add_vote(object)
else
temporary_user.public_send("add_#{object.class.to_s.downcase}", object)
end
return temporary_user
end
def remove_object(object)
if object.class.to_s =~ /Vote/
remove_vote(object)
else
public_send("remove_#{object.class.to_s.downcase}", object)
end
end
def parsed_votes
JSON.parse(votes || {'question' => {}, 'answer' => {}}.to_json)
end
def add_vote(vote)
pv = parsed_votes
topic = vote.topic.downcase
topic_id = vote.topic_id.to_s
existing_vote_id = pv[topic][topic_id]
if (existing_vote = vote.class.find_by(id: existing_vote_id)).present?
existing_vote.update(trust: vote.trust)
vote.destroy
else
pv[topic][topic_id] = vote.id
update(votes: pv.to_json)
end
end
def parsed_questions
JSON.parse(questions || {}.to_json)
end
def add_question(question)
pq = parsed_questions
pq[question.id.to_s] = true
update(questions: pq.to_json)
end
def owns_question?(question)
parsed_questions[question.id.to_s]
end
def parsed_answers
JSON.parse(answers || {}.to_json)
end
def add_answer(answer)
pa = parsed_answers
pa[answer.id.to_s] = true
update(answers: pa.to_json)
end
def parsed_flags
JSON.parse(flags || {'question' => {}, 'answer' => {}}.to_json)
end
def add_flag(flag)
pf = parsed_flags
if flag.question_id.present?
pf['question'][flag.question_id.to_s] = flag.id
else
pf['answer'][flag.answer_id.to_s] = flag.id
end
update(flags: pf.to_json)
end
def remove_flag(flag)
pf = parsed_flags
if flag.question_id.present?
pf['question'].delete flag.question_id.to_s
else
pf['answer'].delete flag.answer_id.to_s
end
update(flags: pf.to_json)
end
end
|
require 'rack/proxy'
module VueCli
module Rails
class DevServerProxy < ::Rack::Proxy
def initialize(app)
@app = app
config = Configuration.instance
@host = config.dev_server_host
@assets_path = config.output_url_path
end
def perform_request(env)
if env['PATH_INFO'].start_with?(@assets_path)
env['HTTP_HOST'] = env['HTTP_X_FORWARDED_HOST'] = env['HTTP_X_FORWARDED_SERVER'] = @host
env['HTTP_X_FORWARDED_PROTO'] = env['HTTP_X_FORWARDED_SCHEME'] = 'http'
env['SCRIPT_NAME'] = ''
super(env)
else
@app.call(env)
end
end
end
end
end
|
# frozen_string_literal: true
FactoryGirl.define do
factory :car do
brand "Ford"
model "Focus"
production_year "2010"
comfort "basic"
places 4
color "black"
category "hatchback"
user
factory :car_with_photo do
car_photo { File.open(Rails.root.join("spec", "fixtures", "images", "car_photo.jpg")) }
end
end
factory :other_car, class: Car do
brand "Opel"
model "Astra"
production_year "2016"
comfort "luxury"
places 5
color "red"
category "sedan"
user
factory :other_car_with_photo do
car_photo { File.open(Rails.root.join("spec", "fixtures", "images", "other_car_photo.jpg")) }
end
end
end
|
require 'spec_helper'
describe "Escapes show request" do
let!(:escape) { FactoryGirl.create(:escape, :title => "Testing Specs",
:expiration => (Time.now.to_date + 7),
:nearest_metro => "Wookieland") }
let!(:metro) { FactoryGirl.create(:metro, :name => "Wookieland") }
let!(:unique_song) { FactoryGirl.create(:unique_song, :metro_id => metro.id) }
let!(:unique_song2) { FactoryGirl.create(:unique_song, :metro_id => metro.id) }
let!(:unique_song3) { FactoryGirl.create(:unique_song, :metro_id => metro.id) }
let!(:unique_song4) { FactoryGirl.create(:unique_song, :metro_id => metro.id) }
let!(:unique_songs) { [unique_song, unique_song2, unique_song3, unique_song4] }
let!(:client) { Nestling.new("123") }
let!(:nestling_response) {
[{:foreign_ids=>[{"catalog"=>"rdio-us-streaming",
"foreign_id"=>"rdio-us-streaming:song:t123456"}],
:artist_id=>"AJFOE813981ALJKL",
:id=>"OIWJF13890JOWI",
:artist_name=>"Notorious BIG",
:title=>"Juicy"}] }
context "when I am redirected from escapes index" do
before(:each) do
Nestling::Playlist.any_instance.stub(:static).and_return(nestling_response)
login
visit escapes_path
page.select("Testing Specs", :from => "escape_id")
click_button("GO")
end
it "takes me to an escape for the category I select" do
current_path.should == escape_path(escape)
page.should have_content("Testing Specs")
end
end
context "when I am logged in and looking at an escape" do
before(:each) do
Nestling::Playlist.any_instance.stub(:static).and_return(nestling_response)
login
visit escape_path(escape)
end
it "shows information about the escape" do
page.should have_content(escape.title)
page.should have_content(escape.location)
page.should have_content(escape.city)
end
it "has a link to view the full details of the escape" do
within("#escape_info") do
page.should have_link("Full Details")
end
end
it "shows the unique songs to the escape's nearest metropolitan area" do
within(".unique") do
page.should have_content(unique_song.artist)
page.should have_content(unique_song.title)
end
end
it "shows links to let me indicate whether I like an escape based on the music" do
within("#votes") do
find("a#upvote").should be_visible
find("a#downvote").should be_visible
end
end
end
end
|
module MRuby
module RubyCompat
module Bundler
def self.setup_standalone_bundle(bundler_setup_file)
Object.const_set(:RbConfig, RbConfig)
root_dir = File.expand_path('../..', bundler_setup_file)
versions = []
Dir.glob(File.join(root_dir, 'ruby', '*')).each do |version_dir|
version = File.basename(version_dir)
versions << version
end
if versions.length > 1
raise "Standalone bundle contains gems from multiple Ruby versions (Versions: #{versions.join(', ')})"
elsif versions.length == 0
raise "Standalone bundle does not contain any gems (Versions: #{versions.join(', ')})"
end
version = versions[0]
mruby_dir = File.join(root_dir, RUBY_ENGINE)
unless File.directory?(mruby_dir)
Dir.mkdir(mruby_dir)
end
symlink_source = File.join(root_dir, 'ruby', version)
symlink_target = File.join(root_dir, RUBY_ENGINE, MRUBY_VERSION)
unless File.symlink?(symlink_target)
File.symlink(symlink_source, symlink_target)
end
load bundler_setup_file
end
module RbConfig
CONFIG = {
'ruby_version' => MRUBY_VERSION
}
end
end
end
end
['bundle/bundler/setup.rb', 'gems/bundler/setup.rb'].each do |bundler_setup_file|
if File.exist?(bundler_setup_file)
MRuby::RubyCompat::Bundler.setup_standalone_bundle(bundler_setup_file)
end
end
|
class User < ApplicationRecord
def admin_exist_check
throw :abort if self.admin? && User.where(admin: true).count == 1
end
def admin_exist_check_update
@admin_user = User.where(admin: true)
throw :abort if @admin_user.first == self && @admin_user.count == 1
end
before_destroy :admin_exist_check
before_update :admin_exist_check_update
validates :name, presence: true, length: { maximum: 30 }
validates :email, presence: true, length: { maximum: 200 }, format: { with: /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i }, uniqueness: true
before_validation { email.downcase! }
has_secure_password
validates :password, presence: true, length: { minimum: 6 }
has_many :tasks, dependent: :destroy
end
|
class CreateNodes < ActiveRecord::Migration
def change
create_table :nodes do |t|
t.integer :story_id, null: false
t.integer :parent_id
t.integer :user_id, null: false
t.integer :level, null: false, default: 2
t.text :path
t.text :content, null: false, default: ""
t.timestamps
end
add_index :nodes, :story_id
add_index :nodes, :user_id
end
end
|
class GoogleCalendar
def self.client_secrets(base_url)
Google::APIClient::ClientSecrets.new(
{
web: {
client_id: ENV["GOOGLE_CLIENT_ID"],
client_secret: ENV["GOOGLE_SECRET_KEY"],
redirect_uris: ["#{base_url}/oauth2callback"],
auth_uri: "https://accounts.google.com/o/oauth2/auth",
token_uri: "https://accounts.google.com/o/oauth2/token"
}
}
)
end
def self.fetch_events(auth_client)
Time.zone = ENV["TIMEZONE_STRING"]
service = Google::Apis::CalendarV3::CalendarService.new
service.client_options.application_name = "Deck 7 Widget"
calendar_id = ENV["GOOGLE_CALENDAR_ID"]
response = service.list_events(
calendar_id,
options: { authorization: auth_client },
single_events: true,
order_by: "startTime",
time_min: Time.zone.now.at_beginning_of_day.iso8601,
time_max: Time.zone.now.at_end_of_day.iso8601)
result = Array.new
response.items.each do |item|
result << item if relevant(item)
end
result
end
def self.relevant(event)
!event.start.date_time.nil? &&
event.start.date_time.to_date.day == Time.zone.now.day &&
!event.summary.downcase.include?("mock")
end
end
|
# == Schema Information
#
# Table name: users
#
# id :integer not null, primary key
# email :string default(""), not null
# encrypted_password :string default(""), not null
# reset_password_token :string
# reset_password_sent_at :datetime
# remember_created_at :datetime
# sign_in_count :integer default(0), not null
# current_sign_in_at :datetime
# last_sign_in_at :datetime
# current_sign_in_ip :string
# last_sign_in_ip :string
# created_at :datetime not null
# updated_at :datetime not null
#
# require 'test_helper'
class UsersControllerTest < ActionController::TestCase
include Devise::TestHelpers
test "should be redirected" do
@controller = PagesController.new
get :home
assert_redirected_to new_user_session_path, "User is not redirected!"
end
# test "should sign in" do
# #@request.env["devise.mapping"] = Devise.mappings[:user]
# @controller = PagesController.new
# #@user = User.new("abc@memphis.edu",User.new.send(:password_digest, 'Passw0rd'))
# #sign_in @user
# sign_in User.first
# get :home
# assert_response :success, "User is not signed in!"
# end
# #Users::SessionsControllerTest < ActionController::TestCase
# #UsersControllerTest < ActionController::TestCase
# include Devise::TestHelpers
# # setup do
# # #@controller = SessionsController.new
# # @user = users(:abc)
# # end
# end
# class User::RegistrationsControllerTest < ActionController::TestCase
# # include Devise::TestHelpers # for including devise's actions
# # def setup # this set up default settings for controller
# # @controller = RegistrationsController.new
# # @request = ActionController::TestRequest.new
# # @response = ActionController::TestResponse.new
# # @request.env["devise.mapping"] = Devise.mappings[:user]
# # @user = Registrations.new(username: "John", email: "myemail@email.com")
# # end
# # setup do # this used for setting global variable used in test file
# # @user= users(:one) # users is the fixture file of test in which you can set default data for test environment.
# # end
# # test "should create user" do # then you test cases for controller
# # sign_in users(:one)
# # post :create, users:{email:'test@test.com, password:'XXXX'...}# you can pass arguments for create method. Please check it once, i am not sure about names
# # assert_response :success
# # end
# # end
# def setup
# request.env['devise.mapping'] = Devise.mappings[:user]
# @user = users(:abc)
# end
# test "should get new" do
# get :new
# assert_response :success
# end
# # #test "should login the user" do
# #test "should create user" do
# @request.env["devise.mapping"] = Devise.mappings[:user]
#@controller = RegistrationsController.new
# # @request = ActionController::TestRequest.new
# # @response = ActionController::TestResponse.new
# # @request.env["devise.mapping"] = Devise.mappings[:user]
# user = Registrations.new(username: "John", email: "myemail@email.com")
# sign_up user
# # #@controller = RegistrationsController.new
# # #get :new
# # #post :user_session
# # assert_response :success
# # # new_user_session GET /users/sign_in(.:format) devise/sessions#new
# # # user_session POST /users/sign_in(.:format) devise/sessions#create
# # # get :index
#assert_response :success
# # #assert_not_nil assigns(:users)
# end
# #test "should get new" do
# # get :new
# #assert_response :success
# #end
# #test "should create user" do
# # assert_difference('user.count') do
# # post :create, user: { email: @user.email, password: @user.password }
# #end
# #assert_redirected_to user_path(assigns(:user))
# #end
# #test "should show user" do
# # get :show, id: @user
# #assert_response :success
# #end
# #test "should get edit" do
# # get :edit, id: @user
# #assert_response :success
# #end
# #test "should update user" do
# # patch :update, id: @user, user: { email: @user.email, password: @user.password }
# # assert_redirected_to user_path(assigns(:user))
# #end
# #test "should destroy user" do
# # assert_difference('user.count', -1) do
# # delete :destroy, id: @user
# #end
# #assert_redirected_to users_path
# #end
end
|
class EventsController < ApplicationController
before_action :signed_in_user
before_action :student_user, only: [:new_reservation]
before_action :not_in_past, only: [:new_reservation]
before_action :not_already_attending, only: [:new_reservation]
before_action :correct_admin, only: [:edit, :update, :ads, :announcement, :sales]
# accessible to students
def index
# must filter out past events
if params[:search] and params[:search] != ''
@events = Event.where('start > ? AND name LIKE ?', Time.now, '%' + params[:search] + '%')
else
@events = Event.where('start > :now', now: Time.now)
end
end
def show
@event = Event.find(params[:id])
@post = @event.posts.build(event_id: @event.id)
@posts = @event.posts.take(@event.posts.size-1) # must slice off the anonymous new post
@tickets_remaining = tickets_remaining
end
def new_reservation # STUDENTS ONLY
@event = Event.find(params[:id])
@ticket_reservation = current_user.ticket_reservations.build(event_id: @event.id)
# must slice off the anonymous reservation
@ticket_reservations = @event.ticket_reservations.take(@event.ticket_reservations.size-1)
@tickets_remaining = tickets_remaining
render 'show_new_reservation'
end
# accessible to club admins
def new
@event = Event.new
end
def create
@event = Event.new(event_params)
@event.club_id = current_user.club.id
if @event.save
current_user.club.add_event(@event)
flash[:success] = "Event created."
redirect_to @event
else
render 'new'
end
rescue ArgumentError
flash[:error] = "Error. Please start over."
@event = Event.new
render 'new'
end
# admin toolbox
def ads
@event = Event.find(params[:id])
render 'show_ads'
end
def announcements
@event = Event.find(params[:id])
render 'show_announcements'
end
def sales
@event = Event.find(params[:id])
@reservations = @event.ticket_reservations
@total_sales = (@event.ticket_price * @reservations.sum(:num_tickets)).to_s
render 'show_sales'
end
def edit
@event = Event.find(params[:id])
end
def update
@event = Event.find(params[:id])
if @event.update_attributes(event_params)
flash[:success] = "Event updated"
redirect_to @event
else
render 'edit'
end
end
def destroy
Event.find(params[:id]).destroy
flash[:success] = "Event deleted."
redirect_to events_admin_path ({id: current_user.id})
end
private
def event_params
params.require(:event).permit(:name, :start, :end,
:location, :description, :ticket_price, :initial_tickets_avail,
:ticket_purchase_instructions, :sales_start, :sales_end, :conditions,
:website_URL, :banner)
end
def tickets_purchased?
!@event.ticket_reservations.empty?
end
def tickets_remaining
if tickets_purchased?
@event.initial_tickets_avail - @event.ticket_reservations.sum(:num_tickets)
else
@event.initial_tickets_avail
end
end
def signed_in_user
redirect_to signin_url, notice: "Please sign in." unless signed_in?
end
def correct_admin
@event = Event.find(params[:id])
@club = Club.find_by(id:@event.club_id)
@admin = Admin.find_by(id: @club.admin_id) # the correct admin of this event's club
redirect_to root_url, notice: "Access denied." unless current_user?(@admin)
end
def student_user
redirect_to event_path, notice: "Only student users are permitted to make ticket reservations." unless student?
end
def not_already_attending
@event = Event.find(params[:id])
redirect_to event_path, notice: "You are already attending the event." if @event.students.exists?(id: current_user.id)
end
def not_in_past
@event = Event.find(params[:id])
redirect_to event_path, notice: "That event already occurred." if @event.start < Time.now
end
end
|
require 'minitest/spec'
require 'minitest/autorun'
require 'redis'
require "#{File.dirname(__FILE__)}/../lib/turnstile"
def turnstile
redis = Redis.new
redis.flushall
Turnstile::Model::Turnstile.new(redis)
end
describe Turnstile::Model::Turnstile do
describe "realms" do
it "should be creatable" do
t = turnstile
t.realms.create("kingdom")
fail if t.realms.find("kingdom").blank?
pass
end
it "should be destroyable" do
t = turnstile
t.realms.create("kingdom")
fail if t.realms.find("kingdom").blank?
t.realms.destroy("kingdom")
fail unless t.realms.find("kingdom").blank?
pass
end
end
describe "users" do
it "should be creatable" do
t = turnstile
t.users.create("king")
fail if t.users.find("king").blank?
pass
end
it "should be addable to a realm" do
t = turnstile
t.realms.create("kingdom")
t.users.create("king")
t.users.add_realm("kingdom", "king", "king")
fail if t.users.in_realm?("kingdom", "king").blank?
pass
end
it "should be able to change their passwords" do
end
it "should be destroyable" do
end
end
describe "roles" do
it "should be addable to a user" do
end
it "should be removable" do
end
end
end
#require 'redis'
#require "#{File.dirname(__FILE__)}/turnstile"
#
#def turnstile
# redis = Redis.new
# redis.flushall
#
# Turnstile::Model::Turnstile.new(redis)
#end
#
#t = turnstile
#t.realms.create("kingdom")
#t.roles.create("royalty")
#t.users.create("king")
#t.users.add_realm("kingdom", "king", "king")
#t.users.realms("king")
#t.realms.add_role("kingdom", "royalty")
#t.realms.roles("kingdom")
#t.users.add_role("kingdom", "king", "royalty")
#t.users.signin "kingdom", "king", "king"
#t.users.authorized? "kingdom", "king", "royalty"
#t.roles.find("royalty")
#t.users.roles("kingdom", "king")
#t.users.find("king") |
require 'rails_helper'
feature 'Footer' do
context "anybody visits home page" do
before { visit root_path }
specify "she sees correct footer links" do
expect(page).to have_link "Home", href: root_path
expect(page).to have_link "Contact", href: contact_new_path
expect(page).to have_link "Services", href: services_path
end
end
end
|
require "language/go"
class Peco < Formula
homepage "https://github.com/peco/peco"
url "https://github.com/peco/peco/archive/v0.2.12.tar.gz"
sha1 "4f5caf6eab2f7c08191939dec7543afc32a6ddde"
bottle do
cellar :any
sha1 "c266e3919d01293aedfc7f4ce459be76ccacd954" => :yosemite
sha1 "9374ae50643d4b8b0e1d09c4b2076e5d3ee09355" => :mavericks
sha1 "a8e68353239ec1b48866f820b8e3c7915b6b5ec9" => :mountain_lion
end
go_resource "github.com/jessevdk/go-flags" do
url "https://github.com/jessevdk/go-flags.git",
:revision => "5e118789801496c93ba210d34ef1f2ce5a9173bd"
end
go_resource "github.com/mattn/go-runewidth" do
url "https://github.com/mattn/go-runewidth.git",
:revision => "c718ccb0685f9fa7129b1b41c04d2877423c419d"
end
go_resource "github.com/nsf/termbox-go" do
url "https://github.com/nsf/termbox-go.git",
:revision => "1f1918bf12614154995c633122959e84e54ffafa"
end
go_resource "github.com/peco/peco" do
url "https://github.com/peco/peco.git",
:revision => "f0c506536a5bb4a0e605fb71420690f57087f2d4"
end
depends_on "go" => :build
def install
ENV["GOPATH"] = buildpath
Language::Go.stage_deps resources, buildpath/"src"
system "go", "build", "cmd/peco/peco.go"
bin.install "peco"
end
test do
system "#{bin}/peco", "--version"
end
end
|
module Admin
class MenusController < AdminBaseController
before_action :load_menu, except: %i(index create)
def index
@menu = Menu.new
@menus = Menu.lastest
end
def show
@dishes = @menu.dishes.distinct
@menudetail = @menu.picks.build
end
def edit; end
def create
@menu = Menu.new menu_params
if @menu.save
flash[:success] = t ".message_success"
else
flash[:danger] = t ".message_danger"
end
redirect_back fallback_location: admin_menus_url
end
def destroy
if @menu.destroy
flash[:success] = t ".deleted"
else
flash[:danger] = t ".not_delete"
end
redirect_back fallback_location: admin_menus_url
end
def update
if @menu.update_attributes menu_params
flash[:success] = t ".updated"
else
flash[:danger] = t ".not_update"
end
redirect_back fallback_location: admin_menus_url
end
private
def menu_params
params.require(:menu).permit :name
end
def load_menu
@menu = Menu.find_by id: params[:id]
return if @menu
flash[:danger] = t ".not_found"
redirect_to admin_url
end
end
end
|
require 'test_helper'
require 'test/unit'
require_relative '../lib/util.rb'
class TestUtil < Test::Unit::TestCase
def test_load_config
plan, contacts, mail_config = load_config_data(File.expand_path('../../dat.yml', __FILE__))
assert(contacts.size >= 1)
assert_equal(plan.keys, ['public', 'discount', 'data'])
assert_not_nil(mail_config['attachment'])
assert_not_nil(mail_config['account']['hostname'])
assert_not_nil(mail_config['account']['port'])
assert_not_nil(mail_config['account']['username'])
assert_not_nil(mail_config['account']['password'])
end
end
|
class InfinityPoint
def +(other)
return other
end
def -(other)
return -other
end
def -@
return self
end
def *(scalar)
return self
end
def eql?(other)
return other.is_a? InfinityPoint
end
def hash
return 1234
end
def to_s
"<Point at Infinity>"
end
end
|
class ImagesController < ApplicationController
before_action :set_image, only: [:show, :edit, :update, :destroy]
before_action :authenticate_user!, except: [:index, :show]
def index
@images = Image.all
@instaimages = Image.last
end
def show
end
def new
@image = current_user.images.build
end
def edit
end
def create
@image = current_user.images.build(image_params)
if @image.save
redirect_to pages_admin_path, notice: 'image was successfully created.'
else
render action: 'new'
end
end
def update
if @image.update(image_params)
redirect_to pages_admin_path, notice: 'image was successfully updated.'
else
render action: 'edit'
end
end
def destroy
@image.destroy
redirect_to pages_admin_path
end
private
def set_image
@image = Image.find(params[:id])
end
def image_params
params.require(:image).permit(:description, :image)
end
end
|
class UserMailer < ApplicationMailer
default from: "owner@address_book.com"
def shared(email, user)
@user = user
mail(to: email, subject: 'Shared email')
end
end
|
# WRONG WAY!
if ! tweets.empty?
puts "Timline:"
puts tweets
end
# GOOD WAY!
# Instead of if ! use unless
unless tweets.empty?
puts "Timline:"
puts tweets
end
# WRONG WAY!
if attachment.file_path != nill
attachement.post
end
# GOOD WAY!
#nil id=s treated ad false
if attachment.file_path != nill
attachement.post
end
# true
"" - is treated as true
0 - is treated as true
[] - is treated as true
#INLINE CONDITION
if password.length < 8
fail "Password to short"
end
fail "Password to short" if password.length < 8
# CONDITION RETURN VALUE
# if always returns value
if list_name
options[:path] = "/#{user_name}/#{list_name}"
else
options[:path] = "/#{user_name}"
end
options[:path] = if list_name
"/#{user_name}/#{list_name}"
else
"/#{user_name}"
end
# HASH ARGUMENTS
def tweet(message, options = {})
status = Status.new
status.lat = options[:lat]
status.long = options[:long]
status.body = message
status.reply_id = options[:reply_id]
status.post
end
# call method shows the meaing of the options
tweet("Practicint Ruby-Fu!",
:lat => 28.55,
:long => -81.09,
:reply_id => 123123123
)
# EXCEPTIONS (if ! to samo co unless)
def get_tweets(list)
unless list.authorised?(@user)
raise AuthorizationException.new
end
list.tweets
end
begin
tweets = get_tweets(my_list)
rescue AuthorizationException
warn "You are not authorozed to access this list"
end
end
# SPLAT ARGUMENTS
def mentions(status, *names)
tweet("#{names.join(' ')} #{status}")
end
# status -> 'Your course rocks!', names[0] -> 'John', names[1] -> 'Thomas', names[2] ->'Json'
mention('Your course rocks!', 'John', 'Thomas', 'Json')
# CLASS #
class Name
def initialize(first, last = nil)
@first = first
@last = last
end
def format
[@last, @first].compact.join(', ')
end
end
user_names = []
user_names << Name.new('Bartosz', 'Kita')
user_names << Name.new('Bartoszek', 'Kowal')
user_names << Name.new('Kita')
user_names.each {|name| name.format}
### ACTIVESUPPORT ###
gem install ACTIVESUPPORT
gem install i18n
require 'active_support/all'
- ARRAY -
array = [1,2,3,4,5,6,7,8]
array.from[4] -> returns new array starrintg from posiotion 4
arry.to(2) -> return new array from the beginning to the position we pass as an argument
array.in_groups_of(3) -> splits the array into [[1,2,3], [4,5,6], [7,8,nil]]
array.split(2) -> split the arrays at the index that was passed !!!! removes the element that was split on !!!! -> [[1,3],[4,5,6,7,8]]
- DATE -
apocalipse = DateTime.new(2012, 12, 12, 14, 27, 45) -> Fri, 21 Dec 2012 14:27:45
apocalipse.at_beginning_of_day -> Fri, 21 Dec 2012 00:00:00
apocalipse.at_end_of_month -> Mon, 31 Dec 2012 23:59:59
apocalipse.at_beginning_of_year -> Sun, 01 Jan 00:00:00
apocalipse.advance(years: 4, months: 2, weeks: 2, days: 12)
apocalipse.tomorrow
apocalipse.yesterday
- HASH -
options = {user: 'codeschool', lang: 'fr'}
new_options = {user: 'codeschool', lang: 'fr', password: 'dunno'}
options.diff(new_options) -> {password: 'dunno'}
options.stringnify_keys -> {"user" => "codeschool", "lang" => "fr"}
options = {user: 'codeschool', lang: 'fr'}
default = {lang: 'en', country: 'us'}
options.reverse_merge(default) => {user: 'codeschool', lang: 'fr', country: 'us'}
new_options.except(:password) -> removes :password -> {user: 'codeschool', lang: 'fr'}
new_options.assert_valid_keys(:user, :lang) -> throws an exception if the hash contains any keys beside those listed here
-> Unknown key(s): passwoed (ArgumentError)
### PROC / LAMBDA / BLOCK ###
### Proc Object ###
my_proc = Proc.new {puts "tweet"}
my_proc.call # => tweet
# the same
my_proc = Proc.new do
puts "tweet"
end
my_proc.call # => tweet
### Lambda ###
my_proc = lambda {puts "tweet"}
my_proc.call # => tweet
# the same (from ruby 1.9)
my_proc = -> {puts "tweet"}
my_proc.call # =>
### block vs. lambda ###
# block + yield
class Tweet
def post
if authenticated?(@user, @password)
yield
elsif
raise 'Auth Error'
end
end
end
tweet = Tweet.new('Ruby Bits!')
tweet.post { puts "Sent!" }
# lambda
class Tweet
def post(success, error)
if authenticated?(@user, @password)
success.call
elsif
error.call
end
end
end
tweet = Tweet.new('Ruby Bits!')
success = -> { puts "Sent!" }
error = -> { raise 'Auth Error' }
tweet.post(success, error)
## & 1.lambda to block
# block
tweets = ["First tweet", "Second tweet"]
tweet.each do |tweet|
puts tweet
end
# &block - changes labda (proc) to block
tweets = ["First tweet", "Second tweet"]
printer = lambda { |tweet| puts tweet }
tweets.each(&printer) # & proc to block
## & 2.block to proc
# defining a method with & in front of a parameter
# turns a block into a proc
# so it can be assigned to a parameter
def each(&block)
end
class Timline
attr_accessor :tweets
def each
tweets.each { |tweet| yield tweet }
end
end
timeline = Timline.new(tweets)
timeline.each do |tweet|
puts tweet
end
# the same using &block
class Timeline
attr_accessor :tweets
def each(&block) #block into proc
tweets.each(&block) # proc back into a block
end
end
# optional block
class Timeline
attr_accessor :tweets
def print
if block_given?
tweets.each { |tweet| puts yield tweet }
else
puts tweets.join(", ")
end
end
end
timeline = Timeline.new
timeline.tweets = ["One, Two"]
# print without block
timeline.print # => One, Two
# print with block
timeline.print { |tweet|
"tweet: #{tweet}"
}
### Closure ###
# current state of local variables is
# preserved when a lambda is created
def tweet_as(user)
lambda { |tweet| puts "#{user}: #{tweet}"}
end
#creating a lambda
greeg_tweet = tweet_as("greegpollack")
# => resolves as: lambda { |tweet| puts "greegpollack: #{tweet}" }
greeg_tweet.call("Awesome!") # => gregpollack: Awesome!
### MODULES ###
# MIXIN - including module into the class
# Use extend to expose
# methods as a class method
# extend = static -> Class.method
class Tweet
extend Searchable
end
module Searchable
def find_all
end
end
Tweet.find_all
# Use include to expose
# methods as instance method
# include = object.method
class Image
include ImageUtils
end
module ImageUtils
def preview
end
end
image = user.imageimage.preview
# MIXIN - for object
class Image
end
module ImageUtils
def preview
end
end
image1 = Image.new
image.extend(ImageUtils) # Only this object can use methods from ImageUtils
image.preview
image2 = Image.new
image.preview
NoMethodError: undefined method 'prevew' for image2
|
FactoryBot.define do
factory :comment do
comment { Faker::Lorem.paragraphs }
user
concert
end
end
|
# frozen_string_literal: true
class Api::V1::Users::Mailer < Devise::Mailer
helper :application # gives access to all helpers defined within `application_helper`.
include Devise::Controllers::UrlHelpers # Optional. eg. `confirmation_url`
def confirmation_instructions(record, token, opts = {})
mail = super
# your custom logic
mail.subject = 'Spolyzer登録確認メール'
mail
end
def reset_password_instructions(record, token, opts = {})
@token = token
devise_mail(record, :reset_password_instructions, opts)
end
def unlock_instructions(record, token, opts = {})
@token = token
devise_mail(record, :unlock_instructions, opts)
end
def email_changed(record, opts = {})
devise_mail(record, :email_changed, opts)
end
def password_change(record, opts = {})
devise_mail(record, :password_change, opts)
end
end
|
# frozen_string_literal: true
require 'weakref'
require_relative 'memory_cache/lock'
require_relative 'memory_cache/entry'
require_relative 'memory_cache/node'
require_relative 'memory_cache/linked_list'
require_relative 'memory_cache/maintainer'
module Super
class MemoryCache
include Super::Component
inst_accessor :max_size
interface :read,
:write,
:fetch,
:expire,
:flush,
:prune,
:size,
:stored?
def initialize
@lock = Lock.new
@data = LinkedList.new
@index = {}
@max_size = 1_000
@maintainer = Maintainer.bootstrap(self)
end
def read(key)
@lock.synchronize do
return unless @index.key?(key)
node = @index[key]
entry = node.value
return if entry.expired?
bump(node)
Marshal.load(entry.payload)
end
end
def write(key, value, options = {})
@lock.synchronize do
stored?(key) ? replace(key, value, options) : store(key, value, options)
end
end
def expire(key)
@lock.synchronize do
return unless stored?(key)
node = @index[key]
remove(node)
end
end
def fetch(key, options = {})
return read(key) if stored?(key)
@lock.synchronize(:fetch) do
stored?(key) ? read(key) : write(key, yield, options)
end
end
def stored?(key)
@index.key?(key) && !@index[key].value.expired?
end
def flush
@data.flush
@index = {}
end
def size
@data.size
end
def prune
@lock.synchronize do
until @data.size <= @max_size
least_used = @data.first
remove(least_used)
end
end
end
private
def store(key, value, options = {})
ttl = options.fetch(:ttl, 10 * 60)
entry = Entry.new(key, Marshal.dump(value), expires_at: generate_expiration(ttl))
node = Node.new(entry)
@index[key] = node
@data.append(node)
prune
value
end
def replace(key, value, options = {})
ttl = options.fetch(:ttl, 10 * 60)
node = @index[key]
node.value.tap do |entry|
entry.payload = Marshal.dump(value)
entry.expires_at = generate_expiration(ttl)
end
bump(node)
value
end
def remove(node)
@data.remove(node)
@index.delete(node.value.key)
end
def bump(node)
@data.swap(node, @data.last)
end
def generate_expiration(ttl)
Time.now.utc + ttl
end
end
end
|
module NdrError
# Global controller logic
class ApplicationController < ActionController::Base
before_action :authenticate
# Ensure Rails doesn't find any host layouts first:
layout 'ndr_error/ndr_error'
helper NdrUi::BootstrapHelper
private
def authenticate
return if NdrError.check_current_user_authentication.call(self)
flash[:error] = 'You are not authenticated.'
redirect_to main_app.url_for('/')
end
# Split out delimited search terms of more than 3 characters in length.
def extract_keywords(query, split_on_space = true)
splitter = split_on_space ? %r{[,;\\/\s]+} : %r{[,;\\/]+}
(query || '').split(splitter).reject { |k| k.length < 3 }
end
end
end
|
require 'tk'
require 'tkextlib/tile' #Advanced GUI
require_relative '../WinBoxes'
require_relative '../Engineering'
require_relative 'GUI/MC9090 RMA GUI.rb'
require_relative 'Scripts/MC9090 RMA.rb'
=begin
#Ocra command for tk:
#ocra "MC9090 RMA GUI.rbw" --windows C:\Ruby193\lib\tcltk\ --no-autoload --add-all-core
=end
$EngineerConsoleLink=""
$title='Waitrose MC9090/MC9091 GUI'
if defined?(Ocra)
#Let Ocra pick up the encryption...
testy = Crypt::Blowfish.new("1").encrypt_string("Moose")
p testy
#Webdriver...
testy = Watir::Browser.new
testy.close
MechReporter.new
exit
end
begin #ErrorHandler
GUI = MC9090RMA_Gui.new
class RDT;def puts(*args);GUI.gui_puts(args.join($/));end;end
GUI.run
#ErrorHandler
rescue #Report on any error and quit
puts %Q|Fatal error occurred:\n#{$!}\n\nDebugging Information:\n#{$@}|,"Error" #Logfile output
exit
ensure #This will execute even after an error
end #ErrorHandler
|
FactoryBot.define do
factory :target_group do
name { Faker::Job.field }
external_id { Faker::IDNumber.valid }
parent_id { nil }
secret_code { Faker::IDNumber.valid }
panel_provider_id { Faker::Number.between(1, 10) }
end
end |
# frozen_string_literal: true
module Sentry
# @api private
class ReleaseDetector
class << self
def detect_release(project_root:, running_on_heroku:)
detect_release_from_env ||
detect_release_from_git ||
detect_release_from_capistrano(project_root) ||
detect_release_from_heroku(running_on_heroku)
end
def detect_release_from_heroku(running_on_heroku)
return unless running_on_heroku
ENV['HEROKU_SLUG_COMMIT']
end
def detect_release_from_capistrano(project_root)
revision_file = File.join(project_root, 'REVISION')
revision_log = File.join(project_root, '..', 'revisions.log')
if File.exist?(revision_file)
File.read(revision_file).strip
elsif File.exist?(revision_log)
File.open(revision_log).to_a.last.strip.sub(/.*as release ([0-9]+).*/, '\1')
end
end
def detect_release_from_git
Sentry.sys_command("git rev-parse --short HEAD") if File.directory?(".git")
end
def detect_release_from_env
ENV['SENTRY_RELEASE']
end
end
end
end
|
require 'rails_helper'
describe Mutations::UserMutationType do
it 'defines a field signInUser that returns Types::UserType type' do
expect(subject).to have_a_field(:signInUser).that_returns(Types::UserType)
end
context 'with signInUser field' do
let(:facebook) { Faker::Omniauth.facebook }
let(:access_token) { facebook[:credentials][:token] }
let(:me) {
{
"id" => facebook[:uid],
"name" => facebook[:info][:name],
"email" => facebook[:info][:email]
}
}
let(:social_api) { double("social_api") }
let(:args) { { provider: 'facebook' } }
let(:ctx) { {
api: {
provider: 'facebook',
social_api: social_api
}
} }
it 'create or find a user' do
allow(social_api).to receive(:get_object).and_return(me)
result = subject.fields['signInUser'].resolve(nil, args, ctx)
expect(result.id).not_to be_nil
end
describe 'a mutation is given' do
let(:vars) { { provider: "facebook" } }
let(:result) { TextblogSchema.execute(mutate_string, variables: vars, context: ctx) }
context 'to sign in user' do
let(:mutate_string) { %|mutation SignInUser($provider: String!) { signInUser(provider: $provider) { id name } }| }
it 'returns a user info' do
allow(social_api).to receive(:get_object).and_return(me)
result_user = result["data"]["signInUser"]
expect(result_user["id"]).not_to be_nil
expect(result_user["name"]).to eq(me["name"])
end
end
end
end
end |
#
# Copyright 2011 National Institute of Informatics.
#
#
# 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.
class ProposalsController < ApplicationController
def index
@proposals = Proposal.all
respond_to do |format|
format.html
format.json { render :json => JSON.pretty_generate(@proposals.as_json) }
end
end
def new
@proposal = Proposal.new
if !params.has_key? :software
@proposal.software = Software.all[0]
else
@proposal.software = Software.find params[:software]
end
@proposal.software.config_item_defaults.each do |config_item_default|
config_item = ConfigItem.new
config_item.config_item_default = config_item_default
config_item.value = config_item_default.value
@proposal.config_items << config_item
end
@proposal.software.components.all.each do |component|
node_config = NodeConfig.new
node_config.component = component
node_config.state = "init"
@proposal.node_configs << node_config
component.component_config_defaults.each do |component_config_default|
component_config = ComponentConfig.new
component_config.component = component
component_config.component_config_default = component_config_default
component_config.content = component_config_default.content
@proposal.component_configs << component_config
end
end
logger.debug @proposal.component_configs
@proposal.software.software_config_defaults.each do |software_config_default|
software_config = SoftwareConfig.new
software_config.software = @proposal.software
software_config.software_config_default = software_config_default
software_config.content = software_config_default.content
@proposal.software_configs << software_config
end
end
def create
if params[:format] == "json"
_change_params
end
_strip_contents_in_params
@proposal = Proposal.new(params[:proposal])
@proposal.state = "init"
if @proposal.save
respond_to do |format|
format.html { redirect_to(proposals_url) }
format.json { render :json => JSON.pretty_generate(@proposal.as_json), :status => :created, :location => @proposal }
end
else
respond_to do |format|
format.html { render :action => "new" }
format.json { render :json => {:errors => @proposal.errors}.as_json }
end
end
end
def show
@proposal = Proposal.find(params[:id])
respond_to do |format|
format.html
format.json { render :json => JSON.pretty_generate(@proposal.as_json) }
end
end
def edit
@proposal = Proposal.find(params[:id])
if params.has_key? :software
@proposal.software = Software.find params[:software]
end
end
def update
if params[:format] == "json"
_change_params
end
params[:proposal].delete "software_id"
@proposal = Proposal.find(params[:id])
node_config_ids = @proposal.node_configs.collect {|node_config| node_config.id}
new_node_config_ids = params[:proposal][:node_configs_attributes].values.collect {|value| value["id"].to_i}
node_config_ids.each do |node_config_id|
NodeConfig.find(node_config_id).destroy unless new_node_config_ids.include?(node_config_id)
end
_strip_contents_in_params
if @proposal.update_attributes(params[:proposal])
@proposal.state = "init"
@proposal.save
respond_to do |format|
format.html { redirect_to(proposals_url) }
format.json { render :json => JSON.pretty_generate(@proposal.as_json) }
end
else
respond_to do |format|
format.html { render :action => "new" }
format.json { render :json => {:errors => @proposal.errors}.as_json }
end
end
end
def destroy
@proposal = Proposal.find(params[:id])
if @proposal.destroy
Utils.delete_template_from_puppet params[:id]
respond_to do |format|
format.html { redirect_to(proposals_url) }
format.json { render :json => "".as_json }
end
end
end
def install
_process "install"
end
def uninstall
_process "uninstall"
end
def test
_process "test"
end
private
def _change_params
proposal_hash = params[:proposal]
logger.debug params[:proposal].inspect
if (proposal_hash.keys - ["name", "software_desc"]).empty?
software = Software.find_by_desc(proposal_hash["software_desc"])
proposal_hash["software_id"] = software.id
proposal_hash.delete "software_desc"
attributes = {}
index = 0
software.config_item_defaults.each{|default|
attributes[index] = {"config_item_default_id" => default.id, "value" => default.value}
index += 1
}
proposal_hash["config_items_attributes"] = attributes
attributes = {}
index = 0
node = Node.first
software.components.each{|component|
attributes[index] = {"node_id" => node.id, "component_id" => component.id}
index += 1
}
proposal_hash["node_configs_attributes"] = attributes
attributes = {}
index = 0
software.components.each {|component|
component.component_config_defaults.each {|default|
attributes[index] = {"component_id" => component.id, "component_config_default_id" => default.id, "content" => default.content}
index += 1
}
}
proposal_hash["component_configs_attributes"] = attributes
attributes = {}
index = 0
software.software_config_defaults.each {|default|
attributes[index] = {"software_id" => software.id, "software_config_default_id" => default.id, "content" => default.content}
index += 1
}
proposal_hash["software_configs_attributes"] = attributes
return proposal_hash
end
if proposal_hash.has_key? "software_desc"
proposal_hash["software_id"] = Software.find_by_desc(proposal_hash["software_desc"]).id
proposal_hash.delete "software_desc"
else
proposal_hash["software_id"] = Proposal.find(params[:id]).software_id
end
proposal_hash.fetch("config_items_attributes", {}).each {|index, config_item|
config_item["config_item_default_id"] = ConfigItemDefault.find_by_name(config_item["name"]).id
config_item.delete "name"
}
proposal_hash.fetch("node_configs_attributes", []).each {|index, node_config|
node_config["node_id"] = Node.find_by_name(node_config["node_name"]).id
node_config.delete "node_name"
node_config["component_id"] = Component.find_by_name(node_config["component_name"]).id
node_config.delete "component_name"
}
proposal_hash.fetch("component_configs_attributes", []).each {|index, component_config|
component_config["component_id"] = Component.find_by_name(component_config["component_name"]).id
component_config.delete "component_name"
component_config["component_config_default_id"] = ComponentConfigDefault.find_by_path(component_config["path"]).id
component_config.delete "path"
}
proposal_hash.fetch("software_configs_attributes", []).each {|index, software_config|
software_config["software_id"] = proposal_hash["software_id"]
software_config["software_config_default_id"] = SoftwareConfigDefault.find_by_path(software_config["path"]).id
software_config.delete "path"
}
logger.debug proposal_hash.inspect
end
def _process(operation)
proposal_id = params[:id]
@proposal = Proposal.find proposal_id
@proposal.state = "waiting" unless @proposal.state =~ /ing$/
@proposal.save
waiting_proposal = WaitingProposal.new
waiting_proposal.proposal = @proposal
waiting_proposal.operation = operation
waiting_proposal.save
mq = MessageQueueClient.new
mq.publish({:operation => operation, :params => {:proposal_id => proposal_id}})
mq.close
respond_to do |format|
format.html { redirect_to(proposals_url) }
format.json { render :json => "".as_json }
end
end
def _strip_contents_in_params
if params[:proposal].has_key? :software_configs_attributes
params[:proposal][:software_configs_attributes].each do |key, software_config_attr|
software_config_attr[:content].strip!
end
end
if params[:proposal].has_key? :component_configs_attributes
params[:proposal][:component_configs_attributes].each do |key, component_config_attr|
component_config_attr[:content].strip!
end
end
end
end
|
class AddAdminToNodes < ActiveRecord::Migration
def change
add_column :nodes, :admin, :boolean, :default => false
end
end
|
require("minitest/autorun")
require("minitest/rg")
require_relative("../room.rb")
require_relative("../guest.rb")
require_relative("../song.rb")
class TestRoom < MiniTest::Test
def setup
@guest1 = Guest.new("Waymar Royce")
@guest2 = Guest.new("Lady Stoneheart")
@guest3 = Guest.new("Coldhands")
@guest4 = Guest.new("Howland Reed")
@song1 = Song.new("Stormzy", "Big For your Boots")
@song2 = Song.new("Stevie Wonder", "Sir Duke")
@song3 = Song.new("Alt-J", "Tessellate")
songs = [@song1, @song2, @song3]
@room1 = Room.new("The Jockey Wilson Suite")
end
def test_check_room_name()
assert_equal("The Jockey Wilson Suite", @room1.room_name)
end
# def test_room_has_guests()
# assert_equal("Lady Stoneheart", @guest2.add_guest_to_room)
# end
# def test_pub_has_till
# assert_equal(100.0, @pub.till())
# end
def test_check_guest_into_room
assert_equal(1, @room1.check_in_guest(@guest1).count)
# @room1.check_in_guest(@guest1)
# assert_equal([@guest1], @room1.guests)
end
def test_check_guest_out_of_room
@room1.check_in_guest(@guest1)
@room1.check_in_guest(@guest2)
@room1.check_in_guest(@guest3)
@room1.check_out_guest(@guest3)
assert_equal(2, @room1.guests_in_room())
end
def test_guests_in_room
@room1.check_in_guest(@guest1)
assert_equal(1, @room1.guests_in_room())
end
def test_add_songs_to_room
assert_equal(1, @room1.add_songs_to_room(@song1).count)
end
end
|
require 'leboncoin/items'
module LeBonCoin
module Search
class << self
###
# Load the given URL as a well-formed HTML document
def loadHTML url
require 'open-uri'
require 'nokogiri'
doc = begin
Nokogiri::HTML(open(url))
rescue
nil
end
return doc
end
###
# Parse items from a given URL
def parseItems url, size, items = LeBonCoin::Search::SearchItems.new(url)
doc = loadHTML url
doc.xpath('//table[@id="hl"]/tr').each do |node|
if items.size < size
parseItemNode node, items.createItem
end
end
if items.size < size
doc.xpath('//a[starts-with(text(), "Page suivante")]').each do |node|
parse node['href'], size, items
end
end
return items
end
###
# Parse item from a given XML node.
def parseItemNode(node, item = Hash.new)
# DATE
item["date"] = begin
require 'date'
DateTime.parse(
node.xpath('td[1]')[0].inner_html.strip
.gsub(/ ao.t<br>/, " aug<br>").gsub(/<br>/, " ")
.gsub(/Aujourd'hui/, (Date.today - 0).strftime('%d %b').downcase)
.gsub(/Hier/, (Date.today - 1).strftime('%d %b').downcase)
)
rescue
nil
end
# IMAGE
item["image"] = begin
node.xpath('td[2]/table/tbody/tr[2]/td[2]/a/img')[0]["src"].strip
rescue
nil
end
# TITLE
item["title"] = begin
LeBonCoin::HTMLUtils.convert(node.xpath('td[3]/a')[0].content.strip)
rescue
"UNKNOW TITLE"
end
# LINK
item["link"] = begin
node.xpath('td[3]/a')[0]["href"].strip
rescue
nil
end
# PRICE
item["currency"] = "EUR"
item["price"] = begin
node.xpath('td[3]/text()[3]')[0].content.strip.gsub(/..$/, "").to_i
rescue
nil
end
return parseItem item["link"], item
end
###
# Parse item from a given HTML link.
def parseItem url, item = Hash.new
doc = loadHTML url
# DESCRIPTION
item["description"] = begin
LeBonCoin::HTMLUtils.convert(doc.xpath('//span[@class="lbcAd_text"]').inner_html)
rescue
nil
end
value = begin
doc.xpath('//span[@class="ad_details_400"]/strong').inner_html.strip
rescue
nil
end
# POSTCODE
item["postcode"] = begin
value[/[0-9]+/]
rescue
nil
end
# CITY
item["city"] = begin
value.gsub(/[0-9]+ /, "")
rescue
nil
end
return item
end
end
end
end
|
# frozen_string_literal: true
Rails.application.routes.draw do
# For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html
resources :facts, only: %i[index show] do
get :list, on: :collection
resources :happenings, only: %i[index show] do
resources :tickets, only: %i[create destroy]
end
end
resources :tickets, only: [:index] do
get :list, on: :collection
end
namespace 'editor' do
root 'facts#index'
resources :facts do
get :list, on: :collection
resources :happenings do
resources :tickets, except: %i[show] do
get :export, on: :collection
end
end
end
end
namespace 'admin' do
root 'users#index'
resources :users, only: %i[index show edit update] do
get :list, on: :collection
resources :tickets, only: %i[index]
end
resources :groups do
get :list, on: :collection
end
end
root 'facts#index'
devise_for :users, prefix: 'auth'
end
|
class Api::V1::ScoresController < ApplicationController
before_action :assert_user
before_action :assert_course, only: [:update, :destroy]
# POST /api/scores/scored_groups.json
def scored
@scores = paginate(Api::Group.base.base_users.base_scores.with_users.with_scores(@user.id))
render json: @scores.as_json(Api::Score::Json::LIST)
end
# POST /api/groups/non_scored_groups.json
def non_scored_groups
@groups = paginate(Api::Group.base.base_users.base_scores.with_users)
render json: @scores.as_json(Api::Score::Json::LIST)
end
end
|
class PoorPokemon::Enemy < PoorPokemon::BasePlayer
def initialize(pokeGroup)
@roster = pokeGroup
@currentPokemon = @roster[0]
end
def switch
#switches current pokemon (should be dead) for another valid pokemon
@currentPokemon = @roster.select{|pokemon|pokemon.alive?}.sample
end
def attacks(oppPokemon, diff, move=nil)
#determines how enemy AI attacks depending on difficulty
if move
dmg = @currentPokemon.attacks(oppPokemon, move)
else
if diff == "easy" || diff =='e'
move = @currentPokemon.usableMoves.sample
dmg = @currentPokemon.attacks(oppPokemon, move)
elsif diff == "hard" || diff =="h"
move = @currentPokemon.usableMoves.sort{|moveA,moveB| moveA.dmg<=>moveB.dmg}.last
dmg = @currentPokemon.attacks(oppPokemon, move)
end
end
[dmg, move]
end
end
|
# encoding: utf-8
require File.expand_path(File.dirname(__FILE__) + '/spec_helper')
describe HasEnum do
let :model do
TestModel.new(:category => :stuff, :status => :pending, :state => :done, :speed => :slow)
end
let :human_enums do
{
:category => {
:stuff => 'Stuff',
:things => 'Things',
:misc => 'Misc'
},
:color => {
:red => 'Red',
:green => 'Green',
:blue => 'Blue'
},
:size => {
:small => "Маленький",
:medium => "Средний",
:large => "Большой"
},
:status => {
:pending => 'На рассмотрении',
:failed => "Обработано с ошибкой",
:done => "Завершено"
},
:state => {
:pending => 'Pending',
:failed => 'Failed',
:done => 'Done'
},
:speed => {
:slow => 'Медленный',
:normal => 'Нормальный',
:fast => 'Быстрый'
}
}.with_indifferent_access
end
it "should have has_enum? and has_multiple_enum? methods" do
TestModel.should be_has_enum(:state)
TestModel.should be_has_multiple_enum(:speed)
TestModel.should_not be_has_enum(:some_attribute)
TestModel.should_not be_has_multiple_enum(:status)
end
it "should return values by name symbol" do
TestModel.enums[:state].should eql human_enums[:state].stringify_keys.keys
end
it "should return values by name string" do
TestModel.enums["state"].should eql human_enums[:state].stringify_keys.keys
end
it "should return the values for a given enum attribute" do
TestModel.enums[:category].should eql human_enums[:category].stringify_keys.keys
end
it "should return hash of values with it's translated equivalent" do
TestModel.human_enums[:size].should eql human_enums[:size]
TestModel.human_enums[:status].should eql human_enums[:status]
TestModel.human_enums[:category].should eql human_enums[:category]
end
it "should return hash of enums with hashes of attributes and theirs translated equivalent" do
TestModel.human_enums.should eql human_enums
end
it "should return translated value for attribute" do
TestModel.human_enums[:size][:large].should eql "Большой"
TestModel.human_enums[:color][:red].should eql "Red"
TestModel.human_enums[:status][:done].should eql "Завершено"
end
it "should autodetect all enums if has_enums called" do
AnotherModel.should be_has_multiple_enum(:speed)
AnotherModel.should_not be_has_multiple_enum(:size)
AnotherModel.should be_has_enum(:size)
AnotherModel.should be_has_enum(:status)
end
describe "category enum" do
it "should accept string enum values" do
%w(stuff things misc).each do |value|
model.category = value
model.should be_valid
end
end
it "should accept symbol enum values" do
%w(stuff things misc).each do |value|
model.category = value.to_sym
model.should be_valid
end
end
it "should reject not enum values" do
model.category = "not_listed_in_enum"
model.should_not be_valid
end
it "should accept nil value for the attribute on create" do
model.category = nil
model.should be_valid
end
it "should not accept nil value for the attribute on update" do
model.save
model.category = nil
model.should_not be_valid
end
it "should not accept blank value for the attribute" do
model.category = ' '
model.should_not be_valid
end
it "should normalize empty value for the attribute" do
model.category = ''
model.category.should be_nil
end
it "should define query methods for enum values" do
%w[stuff things misc].each do |value|
model.should respond_to(:"category_#{value}?")
end
end
it "query methods should works" do
model.category = :stuff
model.should be_category_stuff
model.should_not be_category_things
model.should_not be_category_misc
model.category = :things
model.should_not be_category_stuff
model.should be_category_things
model.should_not be_category_misc
model.category = :misc
model.should_not be_category_stuff
model.should_not be_category_things
model.should be_category_misc
end
it "should not define a scope methods for each enum value" do
TestModel.should_not respond_to :category_stuff
TestModel.should_not respond_to :category_things
TestModel.should_not respond_to :category_misc
end
it "should translate category by human_category method" do
model.human_category.should eql 'Stuff'
end
end
describe "color enum" do
it "should define a scope for each enum value" do
model.color = 'red'
model.save
model2 = model.dup
model2.color = :blue
model2.save
TestModel.color_red.all.should eql TestModel.where(:color => 'red').all
TestModel.color_red.should be_one
TestModel.color_blue.should be_one
TestModel.color_green.count.should be_zero
end
it "should accept nil value for the attribute" do
model.color = nil
model.should be_valid
model.save
model.should be_valid
end
it "should accept blank value for the attribute" do
model.color = ''
model.should be_valid
model.save
model.should be_valid
end
end
describe "size enum" do
it "should not define query methods for enum values" do
%w(small medium large).each do |value|
model.should_not respond_to(:"size_#{value}?")
end
end
it "should accept not enum values" do
model.size = 'stuff'
model.should be_valid
end
end
describe "status enum" do
it "should not accept nil value for the attribute" do
model.status = nil
model.should_not be_valid
end
it "should not accept blank value for the attribute" do
model.status = ''
model.should_not be_valid
end
end
describe "speed enum" do
it "should return empty array for nil speed" do
model.speed = nil
model.speed.should eql []
model.should_not be_valid
end
it "empty array is not valid value for speed" do
model.speed = []
model.should_not be_valid
end
it "should support multiple values for attribute" do
model.speed = [:normal, :fast]
model.should be_valid
end
it "should return nil for human_speed if speed not initialized" do
model.speed = []
model.human_speed.should be_nil
end
it "should return array of translated values for human_speed" do
model.speed = [:normal, :fast]
model.human_speed.should eql %w[Нормальный Быстрый]
end
it "should return array of string values for speed, even if initialized by symbols" do
model.speed = [:normal, :fast]
model.speed.should eql %w[normal fast]
end
end
end
|
require 'rails_helper'
describe "Places" do
it "if one is returned by the API, it is shown at the page" do
allow(BeermappingApi).to receive(:places_in).with("kumpula").and_return( [Place.new(name:"Oljenkorsi", id:1)])
visit places_path
fill_in('city', with: 'kumpula')
click_button 'Search'
expect(page).to have_content 'Oljenkorsi'
end
it "if several are returned by the API, all are shown at the page" do
places = [ Place.new(name:"Britannia", id:1) ]
places << Place.new(name:"Kannel Pub", id:2)
allow(BeermappingApi).to receive(:places_in).with("kannelmäki").and_return( places )
visit places_path
fill_in('city', with: 'kannelmäki')
click_button 'Search'
expect(page).to have_content 'Britannia'
expect(page).to have_content 'Kannel Pub'
end
it "if no place is returned by the API, message is shown at the page" do
allow(BeermappingApi).to receive(:places_in).with("kumpula").and_return( [])
visit places_path
fill_in('city', with: 'kumpula')
click_button 'Search'
expect(page).to have_content 'No places in kumpula'
end
end
|
class Category < ApplicationRecord
validates :title, presence: { message: "请输入分类名称" }
has_many :products
end
|
class OrganizationDocumentsDatasetGenerator
include Rails.application.routes.url_helpers
def initialize(organization)
@organization = organization
end
def generate!
dataset = build_dataset
dataset.sector = Sector.friendly.find('otros')
build_distribution(dataset)
dataset.save
end
private
def build_dataset
@organization.catalog.datasets.build do |dataset|
dataset.title = "Oficios y Documentos Institucionales de #{@organization.title}"
dataset.description = "Contiene el Oficio de designación del Enlace y Administrador de Datos vigente, "\
"así como las minutas celebradas por el Consejo Institucional de Datos Abierto de #{@organization.title}."
dataset.accrual_periodicity = 'irregular'
dataset.publish_date = Time.current + 1.week
dataset.contact_position = ENV_CONTACT_POSITION_NAME
dataset.mbox = @organization.administrator&.user&.email
dataset.temporal = "#{Date.current.iso8601}/#{Date.new(2018, 11, 30).iso8601}"
dataset.keyword = 'oficio,minutas,documentos'
dataset.data_dictionary = 'https://datos.gob.mx/guia/docs/oficio_designacion_enlace_administrador.docx'
dataset.editable = false
end
end
def build_distribution(dataset)
dataset.distributions.build do |distribution|
distribution.title = "Oficios y Documentos Institucionales de #{@organization.title}"
distribution.description = "Contiene el Oficio de designación del Enlace y Administrador de Datos vigente, "\
"así como las minutas celebradas por el Consejo Institucional de Datos Abierto de #{@organization.title}."
distribution.download_url = documents_api_v1_organization_url(@organization).to_s
distribution.media_type = 'application/json'
distribution.format = 'json'
distribution.modified = Time.current
distribution.temporal = "#{Date.current.iso8601}/#{Date.new(2018, 11, 30).iso8601}"
distribution.publish_date = Time.current + 1.week
end
end
end
|
require 'active_support/core_ext/hash/indifferent_access'
require 'active_support/core_ext/array/wrap'
require 'active_support/core_ext/hash/slice'
require 'active_support/core_ext/object/blank'
module BlueprintAgreement
class ExcludeFilter
class << self
def deep_exclude(content, exclude_attributes)
return content if content.blank? || !content.is_a?(Hash)
new(exclude_attributes).deep_exclude(content)
end
end
def initialize(exclude_attributes)
@exclude_attributes = exclude_attributes
end
def deep_exclude(content)
return content if @exclude_attributes.nil?
content.with_indifferent_access.tap do |params|
@exclude_attributes.flatten.each do |filter|
case filter
when Symbol, String
params.delete(filter) && params if params.has_key?(filter)
when Hash then
hash_filter(params, filter)
end
end
end
end
private
def hash_filter(params, filter)
filter = filter.with_indifferent_access
params.slice(*filter.keys).each do |key, value|
next unless value
next unless params.has_key? key
if value.is_a?(Array) || value.is_a?(Hash)
params[key] = each_element(value) do |element|
self.class.deep_exclude(element, Array.wrap(filter[key]))
end
end
end
end
def each_element(object)
case object
when Array
object.grep(Hash).map { |el| yield el }.compact
when Hash
if fields_for_style? object
hash = object.class.new
object.each { |k,v| hash[k] = yield v }
hash
else
yield object
end
end
end
def fields_for_style?(object)
object.is_a?(Hash) && object.all? { |k, v| k =~ /\A-?\d+\z/ && v.is_a?(Hash) }
end
end
end
|
class Api::AnswersController < ApplicationController
def create
@answer = Answer.new(answer_params)
@answer.question_id = params[:question_id]
if (current_user)
@answer.author_id = current_user.id
else
@answer.author_id = 1
end
if @answer.save
@user = current_user
@question = @answer.question
render :create
else
render json: {
base: @answer.errors.full_messages
}
end
end
def update
@answer = Answer.find(params[:id])
if @answer.update_attributes(answer_params);
@question = @answer.question
@user = current_user
render :create
else
render json: {
base: @answer.errors.full_messages
}
end
end
def destroy
@answer = Answer.find(params[:id])
@answer.destroy
@question = @answer.question
@user = current_user
render :create
end
private
def answer_params
params.require(:answer).permit(
:content
)
end
end
|
puts "Enter 1 to add, 2 to subtract, 3 to multiply, or 4 to divide two numbers."
operator = gets.to_i
if operator > 4
puts "Invalid entry please enter a number between 1 and 4."
operator = gets.to_i
end
puts "Enter the first number to put in the equation."
number1 = gets.to_i
puts "Enter the second number to put in the equation."
number2 = gets.to_i
def equation1
case math
when 1
result = number1 + number2
when 2
result = number1 - number2
when 3
result = number1 * number2
when 4
result = number1 / number2
end
end
puts "Your answer is #{result}."
puts "Would you like to add, subtract, multiply, or divide from #{result}? Enter yes or no."
continue = gets
#
if continue == "yes"
puts "Enter 1 to add, 2 to subtract, 3 to multiply, or 4 to divide #{result}."
operator = gets.to_i
if operator > 4
puts "Invalid entry please enter a number between 1 and 4."
operator = gets.to_i
end
end
while continue == "yes"
puts "Enter the next number to put in the equation."
new_number = gets.to_i
case operator
when 1
result = result + new_number
when 2
result = result - new_number
when 3
result = result * new_number
when 4
result = result / new_number
end
puts "Your answer is #{result}."
end
if continue == 'no'
puts "Calculator is shutting down."
exit
end |
class AddColumnToAlbums < ActiveRecord::Migration[5.1]
def change
add_column :albums, :band_id, :integer, null: true
add_column :tracks, :album_id, :integer, null: true
end
end
|
class PagesController < ApplicationController
def home
@post = Post.new
@comment = Comment.new
@like = Like.new
@alreadyLiked = false
# When we get to the home page, check if the user is logged in. If so, get the posts for it and chuck it in an array.
if @current_user.present?
# Start off by adding the own users posts to the array.
@posts = @current_user.posts
# Now loop through everyone the user is following and add their posts to the array
@current_user.following.each do |following|
@posts += following.posts
end
# Now sort the array of posts
@posts = @posts.sort_by(&:created_at).reverse
end
end
end
|
class User < ApplicationRecord
authenticates_with_sorcery!
has_many :posts, dependent: :destroy
has_many :comments, dependent: :destroy
validates :name, presence: true, length: { maximum: 50 }
validates :email, presence: true, uniqueness: true
validates :password, presence: true, confirmation: true, length: { minimum: 4 }
validates :password_confirmation, presence: true
validates :sex, presence: true
enum sex: { male: 0, female: 1 }
def is_created_by_user?(user)
user.id == id
end
end
|
class User < ActiveRecord::Base
has_secure_password
def set_password_reset
self.code = SecureRandom.urlsafe_base64
self.expires_at = 4.hours.from_now
self.save!
end
def self.authenticate (email, password)
User.find_by_email(email).try(:authenticate, password)
end
has_one :profile
has_many :users_events
has_many :events, through: :users_events
end
|
class RemoveIntervalFromStationService < ActiveRecord::Migration
def change
remove_column :station_services, :interval, :string
end
end
|
class ManageIQ::Providers::Amazon::CloudManager::Vm < ManageIQ::Providers::CloudManager::Vm
include_concern 'Operations'
include_concern 'ManageIQ::Providers::Amazon::CloudManager::VmOrTemplateShared'
supports :capture
POWER_STATES = {
"running" => "on",
"powering_up" => "powering_up",
"shutting_down" => "powering_down",
"shutting-down" => "powering_down",
"stopping" => "powering_down",
"pending" => "suspended",
"terminated" => "terminated",
"stopped" => "off",
"off" => "off",
# 'unknown' will be set by #disconnect_ems - which means 'terminated' in our case
"unknown" => "terminated",
}.freeze
def provider_object(connection = nil)
connection ||= ext_management_system.connect
connection.instance(ems_ref)
end
def memory_mb_available?
true
end
#
# Relationship methods
#
def disconnect_inv
super
# Mark all instances no longer found as unknown
self.raw_power_state = "unknown"
save
end
#
# EC2 interactions
#
def set_custom_field(key, value)
with_provider_object do |instance|
tags = instance.create_tags({
tags: [
{
key: key,
value: value,
},
],
})
tags.find{|tag| tag.key == key}.value == value
end
end
def self.calculate_power_state(raw_power_state)
# http://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_InstanceState.html
POWER_STATES[raw_power_state.to_s] || "terminated"
end
def self.display_name(number = 1)
n_('Instance (Amazon)', 'Instances (Amazon)', number)
end
end
|
# wkhtml2pdf Ruby interface
# http://wkhtmltopdf.org/
require 'logger'
require 'digest/md5'
require 'rbconfig'
require 'chrome_remote'
require 'base64'
require 'tempfile'
require 'open3'
require 'active_support/core_ext/module/attribute_accessors'
require 'active_support/core_ext/object/blank'
require 'wicked_pdf/version'
require 'wicked_pdf/railtie'
require 'wicked_pdf/option_parser'
require 'wicked_pdf/tempfile'
# require 'wicked_pdf/binary'
require 'wicked_pdf/middleware'
require 'wicked_pdf/progress'
class WickedPdf
DEFAULT_BINARY_VERSION = Gem::Version.new('0.9.9')
BINARY_VERSION_WITHOUT_DASHES = Gem::Version.new('0.12.0')
EXE_NAMES = ['google-chrome', 'Google Chrome Canary', 'Google Chrome'].freeze
@@config = {}
cattr_accessor :config
attr_accessor :binary_version
include Progress
def initialize(chrome_binary_path = nil)
@exe_path = chrome_binary_path || find_chrome_binary_path
raise "Location of #{EXE_NAMES[1]} unknown" if @exe_path.empty?
raise "Bad #{EXE_NAMES[1]}'s path: #{@exe_path}" unless File.exist?(@exe_path)
raise "#{EXE_NAMES[1]} is not executable" unless File.executable?(@exe_path)
end
def binary_version
''
end
def pdf_from_html_file(filepath, options = {})
pdf_from_url("file:///#{filepath}", options)
end
def pdf_from_string(string, options = {})
options = options.dup
options.merge!(WickedPdf.config) { |_key, option, _config| option }
string_file = WickedPdf::Tempfile.new('wicked_pdf.html', options[:temp_path])
string_file.write_in_chunks(string)
pdf_from_html_file(string_file.path, options)
ensure
string_file.close if string_file
end
def generate_port_number
rand(65_000 - 9222) + 9222
end
def try_to_connect(host, port)
@client = ChromeRemote.client host: host, port: port
end
def find_available_port(host)
port = generate_port_number
begin
t = TCPServer.new(host, port)
rescue Errno::EADDRINUSE
port = generate_port_number
retry
end
t.close
port
end
# Launch Chrome headless
def launch_chrome(host, port, debug=false)
options = "--headless --disable-gpu --remote-debugging-port=#{port} about:blank"
cmd = @exe_path.gsub(' ', '\ ') + ' ' + options
print_command(cmd.inspect) if in_development_mode?
pid = spawn(cmd)
Rails.logger.info "Chrome running with pid: #{pid}, remote debugging port: #{port}"
# Wait a bit for Chrome to be fully awake
sleep 2
pid
end
def connect_to_chrome(host, port)
connected = false
retry_count = 0
Rails.logger.info 'Trying to connect...'
until connected && retry_count < 30
begin
retry_count += 1
try_to_connect(host, port)
connected = true
rescue Errno::ECONNREFUSED, SocketError
sleep 0.1
end
end
if connected
Rails.logger.info ' Connected!'
sleep 0.1 # Need to wait a bit here before sending commands
else
Rails.logger.info ' Error: can\'t connect to Chrome'
raise "Couldn't connect to Chrome"
end
end
def pdf_from_url(url, options = {})
# merge in global config options
options.merge!(WickedPdf.config) { |_key, option, _config| option }
host = '127.0.0.1'
port = find_available_port(host)
pid = launch_chrome(host, port)
cmd = @exe_path.gsub(' ', '\ ') + ' ' + url
if options[:debug] && in_development_mode?
Rails.logger.info "Debug mode - opening web page as well"
print_command(cmd.inspect) if in_development_mode?
spawn(cmd)
end
connect_to_chrome(host, port)
@client.send_cmd "Page.enable"
@client.send_cmd "Network.enable"
@client.send_cmd "Page.navigate", url: url
time = Time.now
Rails.logger.info 'Waiting for page to load...'
@client.wait_for "Page.loadEventFired"
Rails.logger.info " #{Time.now - time}s"
Rails.logger.info 'Printing to PDF...'
t = Time.now
pdf_options = {
printBackground: options[:printBackground] || true,
landscape: options[:landscape] || false,
paperHeight: options[:paperHeight] || 11,
paperWidth: options[:paperWidth] || 8.5,
marginTop: options[:marginTop] || 0.4,
marginBottom: options[:marginBottom] || 0.4,
marginLeft: options[:marginLeft] || 0.4,
marginRight: options[:marginRight] || 0.4,
scale: options[:scale] || 1.0,
displayHeaderFooter: options[:displayHeaderFooter] || false,
pageRanges: options[:pageRanges] || '',
headerTemplate: options[:header] && options[:header][:html] ? options[:header][:html][:string] : '',
footerTemplate: options[:footer] && options[:footer][:html] ? options[:footer][:html][:string] : ''
}
data = @client.send_cmd 'Page.printToPDF', pdf_options
pdf = Base64.decode64(data['data'])
Rails.logger.info " PDF generated in #{Time.now - t} sec"
Process.kill 'TERM', pid
Rails.logger.info 'Closing Chrome!'
pid = nil
raise "PDF could not be generated!\n Command Error: #{err}" if pdf && pdf.rstrip.empty?
pdf
ensure
Process.kill 'TERM', pid unless pid.nil?
end
private
def in_development_mode?
return Rails.env == 'development' if defined?(Rails.env)
RAILS_ENV == 'development' if defined?(RAILS_ENV)
end
def on_windows?
RbConfig::CONFIG['target_os'] =~ /mswin|mingw/
end
def print_command(cmd)
Rails.logger.debug '[wicked_pdf]: ' + cmd
end
def parse_options(options)
OptionParser.new(binary_version).parse(options)
end
def find_chrome_binary_path
possible_locations = (ENV['PATH'].split(':') + %w(/usr/bin /usr/local/bin /Applications/Google\ Chrome\ Canary.app/Contents/MacOS /Applications/Google\ Chrome.app/Contents/MacOS)).uniq
possible_locations += %w(~/bin) if ENV.key?('HOME')
exe_path ||= WickedPdf.config[:chrome_path] unless WickedPdf.config.empty?
EXE_NAMES.each do |exe_name|
exe_path ||= possible_locations.map { |l| File.expand_path("#{l}/#{exe_name}") }.find { |location| File.exist?(location) }
end
exe_path || ''
end
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.