text stringlengths 10 2.61M |
|---|
class BinsController < ApplicationController
before_action :set_bin, only: [:destroy]
def update
respond_to do |format|
if @channel.update(channel_params)
format.html { redirect_to @channel, notice: 'Channel was successfully updated.' }
format.json { render :show, status: :ok, location: @channel }
else
format.html { render :edit }
format.json { render json: @channel.errors, status: :unprocessable_entity }
end
end
end
def destroy
@bin.destroy
respond_to do |format|
format.html { redirect_to events_url, notice: 'Bin was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_bin
@bin = Bin.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def channel_params
params.require(:bin).permit!
end
end
|
require 'rails_helper'
RSpec.describe "bookmarks/index", type: :view do
before(:each) do
assign(:bookmarks, [
Bookmark.create!(
:name => "Google",
:url => "http://www.google.com/xyz",
:short_url => "http://goo.gl/xyz",
:site => Site.new(url: "http://www.google.com")
),
Bookmark.create!(
:name => "Google",
:url => "http://www.wikipedia.com/xyz",
:short_url => "http://goo.gl/wik",
:site => Site.new(url: "http://www.wikipedia.com")
)
])
end
it "renders a list of bookmarks" do
render
assert_select "article h2", :text => "Google".to_s, :count => 2
end
end
|
class OwnedResourcesController < ApplicationController
before_filter :identify_parent
# GET /owned_resources
# GET /owned_resources.json
def index
@owned_resources = nil
@title = @org.display_name
if params[:resource_type] == 'Service'
@title += " Services"
@owned_resources = @org.owned_resources.where(:resource_type => 'Service')
elsif params[:resource_type] == 'App'
@title += " Apps"
@owned_resources = @org.owned_resources.where(:resource_type => 'App')
else
@title += "'s Resources"
@owned_resources = @org.owned_resources
end
respond_to do |format|
format.html # index.html.erb
format.json { render :json => @owned_resources }
end
end
# GET /owned_resources/1
# GET /owned_resources/1.json
def show
@owned_resource = @org.owned_resources.find(params[:id])
respond_to do |format|
format.html # show.html.erb
format.json { render :json => @owned_resource }
end
end
# GET /owned_resources/new
# GET /owned_resources/new.json
def new
@owned_resource = @org.owned_resources.build
respond_to do |format|
format.html # new.html.erb
format.json { render :json => @owned_resource }
end
end
# GET /owned_resources/1/edit
def edit
@owned_resource = @org.owned_resources.find(params[:id])
end
# POST /owned_resources
# POST /owned_resources.json
def create
@owned_resource = @org.owned_resources.build(params[:owned_resource])
respond_to do |format|
if @owned_resource.save
flash[:notice] = 'Resource was successfully assigned.'
format.html { redirect_to org_owned_resource_path(@org, @owned_resource) }
format.json { render :json => @owned_resource, :status => :created, :location => @owned_resource }
else
format.html { render :action => "new" }
format.json { render :json => @owned_resource.errors, :status => :unprocessable_entity }
end
end
end
# PUT /owned_resources/1
# PUT /owned_resources/1.json
def update
@owned_resource = @org.owned_resources.find(params[:id])
respond_to do |format|
if @owned_resource.update_attributes(params[:owned_resource])
flash[:notice] = 'Resource was successfully updated.'
format.html { redirect_to org_owned_resource_path(@org, @owned_resource)}
format.json { head :ok }
else
format.html { render :action => "edit" }
format.json { render :json => @owned_resource.errors, :status => :unprocessable_entity }
end
end
end
# DELETE /owned_resources/1
# DELETE /owned_resources/1.json
def destroy
@owned_resource = @org.owned_resources.find(params[:id])
@owned_resource.destroy
respond_to do |format|
format.html { redirect_to(org_owned_resources_url @org) }
format.json { head :ok }
end
end
end
|
require "lib/omniauth-goodreads/version.rb"
Gem::Specification.new do |s|
s.name = "omniauth-goodreads"
s.version = Omniauth::Goodreads::VERSION
s.authors = ["Michael Bleigh"]
s.date = "2012-07-11"
s.description = "An OmniAuth strategy for goodreads."
s.email = "mbleigh@mbleigh.com"
s.extra_rdoc_files = [
"LICENSE",
"README.md"
]
s.files = [
"Gemfile",
"LICENSE",
"README.md",
"omniauth-goodreads.gemspec",
"lib/omniauth/strategies/goodreads.rb"
]
s.homepage = "http://github.com/bsoule/omniauth-goodreads"
s.licenses = ["MIT"]
s.require_paths = ["lib"]
s.summary = "An OmniAuth strategy for goodreads."
end |
##########################GO-LICENSE-START################################
# Copyright 2016 ThoughtWorks, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
##########################GO-LICENSE-END##################################
require 'spec_helper'
def schedule_options(specified_revisions, variables, secure_variables = {})
ScheduleOptions.new(HashMap.new(specified_revisions), LinkedHashMap.new(variables), HashMap.new(secure_variables))
end
describe Api::PipelinesController do
include StageModelMother
include GoUtil
include APIModelMother
before :each do
@pipeline_service = Object.new
@pipeline_history_service = double('pipeline_history_service')
@pipeline_unlock_api_service = double('pipeline_unlock_api_service')
@go_config_service = double('go_config_service')
@changeset_service = double("changeset_service")
@pipeline_pause_service = double("pipeline_pause_service")
@status="status"
controller.stub(:changeset_service).and_return(@changeset_service)
controller.stub(:pipeline_scheduler).and_return(@pipeline_service)
controller.stub(:pipeline_unlock_api_service).and_return(@pipeline_unlock_api_service)
controller.stub(:pipeline_history_service).and_return(@pipeline_history_service)
controller.stub(:go_config_service).and_return(@go_config_service)
controller.stub(:current_user).and_return(@user = "user")
controller.stub(:pipeline_service).and_return(@pipeline_service)
controller.stub(:pipeline_pause_service).and_return(@pipeline_pause_service)
@material_config = double('material_config')
@fingerprint = '123456'
@material_config.stub(:getPipelineUniqueFingerprint).and_return(@fingerprint)
controller.stub(:populate_config_validity)
setup_base_urls
end
it "should return only the path to a pipeline api" do
api_pipeline_action_path(:pipeline_name => "pipeline", :action => "schedule").should == "/api/pipelines/pipeline/schedule"
end
describe :history do
it "should render history json" do
loser = Username.new(CaseInsensitiveString.new("loser"))
controller.should_receive(:current_user).and_return(loser)
@pipeline_history_service.should_receive(:totalCount).and_return(10)
@pipeline_history_service.should_receive(:loadMinimalData).with('up42', anything, loser, anything).and_return(create_pipeline_history_model)
get :history, :pipeline_name => 'up42', :offset => '5', :no_layout => true
expect(response.body).to eq(PipelineHistoryAPIModel.new(Pagination.pageStartingAt(5, 10, 10), create_pipeline_history_model).to_json)
end
it "should render error correctly" do
loser = Username.new(CaseInsensitiveString.new("loser"))
controller.should_receive(:current_user).and_return(loser)
@pipeline_history_service.should_receive(:totalCount).and_return(10)
@pipeline_history_service.should_receive(:loadMinimalData).with('up42', anything, loser, anything) do |pipeline_name, pagination, username, result|
result.notAcceptable("Not Acceptable", HealthStateType.general(HealthStateScope::GLOBAL))
end
get :history, :pipeline_name => 'up42', :no_layout => true
expect(response.status).to eq(406)
expect(response.body).to eq("Not Acceptable\n")
end
describe :route do
it "should route to history" do
expect(:get => '/api/pipelines/up42/history').to route_to(:controller => "api/pipelines", :action => "history", :pipeline_name => 'up42', :offset => '0', :no_layout => true)
expect(:get => '/api/pipelines/up42/history/1').to route_to(:controller => "api/pipelines", :action => "history", :pipeline_name => 'up42', :offset => '1', :no_layout => true)
end
describe :with_pipeline_name_contraint do
it 'should route to history action of pipelines controller having dots in pipeline name' do
expect(:get => 'api/pipelines/some.thing/history').to route_to(no_layout: true, controller: 'api/pipelines', action: 'history', pipeline_name: 'some.thing', :offset => '0')
end
it 'should route to history action of pipelines controller having hyphen in pipeline name' do
expect(:get => 'api/pipelines/some-thing/history').to route_to(no_layout: true, controller: 'api/pipelines', action: 'history', pipeline_name: 'some-thing', :offset => '0')
end
it 'should route to history action of pipelines controller having underscore in pipeline name' do
expect(:get => 'api/pipelines/some_thing/history').to route_to(no_layout: true, controller: 'api/pipelines', action: 'history', pipeline_name: 'some_thing', :offset => '0')
end
it 'should route to history action of pipelines controller having alphanumeric pipeline name' do
expect(:get => 'api/pipelines/123foo/history').to route_to(no_layout: true, controller: 'api/pipelines', action: 'history', pipeline_name: '123foo', :offset => '0')
end
it 'should route to history action of pipelines controller having capitalized pipeline name' do
expect(:get => 'api/pipelines/FOO/history').to route_to(no_layout: true, controller: 'api/pipelines', action: 'history', pipeline_name: 'FOO', :offset => '0')
end
it 'should not route to history action of pipelines controller for invalid pipeline name' do
expect(:get => 'api/pipelines/fo$%#@6/history').to_not be_routable
end
end
end
end
describe :instance_by_counter do
it "should render instance json" do
loser = Username.new(CaseInsensitiveString.new("loser"))
controller.should_receive(:current_user).and_return(loser)
@pipeline_history_service.should_receive(:findPipelineInstance).with('up42', 1, loser, anything).and_return(create_pipeline_model)
get :instance_by_counter, :pipeline_name => 'up42', :pipeline_counter => '1', :no_layout => true
expect(response.body).to eq(PipelineInstanceAPIModel.new(create_pipeline_model).to_json)
end
it "should render error correctly" do
loser = Username.new(CaseInsensitiveString.new("loser"))
controller.should_receive(:current_user).and_return(loser)
@pipeline_history_service.should_receive(:findPipelineInstance).with('up42', 1, loser, anything) do |pipeline_name, pipeline_counter, username, result|
result.notAcceptable("Not Acceptable", HealthStateType.general(HealthStateScope::GLOBAL))
end
get :instance_by_counter, :pipeline_name => 'up42', :pipeline_counter => '1', :no_layout => true
expect(response.status).to eq(406)
expect(response.body).to eq("Not Acceptable\n")
end
describe :route do
describe :with_pipeline_name_contraint do
it 'should route to instance_by_counter action of pipelines controller having dots in pipeline name' do
expect(:get => 'api/pipelines/some.thing/instance/1').to route_to(no_layout: true, controller: 'api/pipelines', action: 'instance_by_counter', pipeline_name: 'some.thing', pipeline_counter: '1')
end
it 'should route to instance_by_counter action of pipelines controller having hyphen in pipeline name' do
expect(:get => 'api/pipelines/some-thing/instance/1').to route_to(no_layout: true, controller: 'api/pipelines', action: 'instance_by_counter', pipeline_name: 'some-thing', pipeline_counter: '1')
end
it 'should route to instance_by_counter action of pipelines controller having underscore in pipeline name' do
expect(:get => 'api/pipelines/some_thing/instance/1').to route_to(no_layout: true, controller: 'api/pipelines', action: 'instance_by_counter', pipeline_name: 'some_thing', pipeline_counter: '1')
end
it 'should route to instance_by_counter action of pipelines controller having alphanumeric pipeline name' do
expect(:get => 'api/pipelines/123foo/instance/1').to route_to(no_layout: true, controller: 'api/pipelines', action: 'instance_by_counter', pipeline_name: '123foo', pipeline_counter: '1')
end
it 'should route to instance_by_counter action of pipelines controller having capitalized pipeline name' do
expect(:get => 'api/pipelines/FOO/instance/1').to route_to(no_layout: true, controller: 'api/pipelines', action: 'instance_by_counter', pipeline_name: 'FOO', pipeline_counter: '1')
end
it 'should not route to instance_by_counter action of pipelines controller for invalid pipeline name' do
expect(:get => 'api/pipelines/fo$%#@6/instance/1').to_not be_routable
end
end
describe :with_pipeline_counter_constraint do
it 'should not route to instance_by_counter action of pipelines controller for invalid pipeline counter' do
expect(:get => 'api/pipelines/some.thing/instance/fo$%#@6/2').to_not be_routable
end
end
end
end
describe :status do
it "should render status json" do
loser = Username.new(CaseInsensitiveString.new("loser"))
controller.should_receive(:current_user).and_return(loser)
@pipeline_history_service.should_receive(:getPipelineStatus).with('up42', "loser", anything).and_return(create_pipeline_status_model)
get :status, :pipeline_name => 'up42', :no_layout => true
expect(response.body).to eq(PipelineStatusAPIModel.new(create_pipeline_status_model).to_json)
end
it "should render error correctly" do
loser = Username.new(CaseInsensitiveString.new("loser"))
controller.should_receive(:current_user).and_return(loser)
@pipeline_history_service.should_receive(:getPipelineStatus).with('up42', "loser", anything) do |pipeline_name, username, result|
result.notAcceptable("Not Acceptable", HealthStateType.general(HealthStateScope::GLOBAL))
end
get :status, :pipeline_name => 'up42', :no_layout => true
expect(response.status).to eq(406)
expect(response.body).to eq("Not Acceptable\n")
end
describe :route do
it "should route to status" do
expect(:get => '/api/pipelines/up42/status').to route_to(:controller => "api/pipelines", :action => "status", :pipeline_name => 'up42', :no_layout => true)
end
describe :with_pipeline_name_contraint do
it 'should route to status action of pipelines controller having dots in pipeline name' do
expect(:get => 'api/pipelines/some.thing/status').to route_to(no_layout: true, controller: 'api/pipelines', action: 'status', pipeline_name: 'some.thing')
end
it 'should route to status action of pipelines controller having hyphen in pipeline name' do
expect(:get => 'api/pipelines/some-thing/status').to route_to(no_layout: true, controller: 'api/pipelines', action: 'status', pipeline_name: 'some-thing')
end
it 'should route to status action of pipelines controller having underscore in pipeline name' do
expect(:get => 'api/pipelines/some_thing/status').to route_to(no_layout: true, controller: 'api/pipelines', action: 'status', pipeline_name: 'some_thing')
end
it 'should route to status action of pipelines controller having alphanumeric pipeline name' do
expect(:get => 'api/pipelines/123foo/status').to route_to(no_layout: true, controller: 'api/pipelines', action: 'status', pipeline_name: '123foo')
end
it 'should route to status action of pipelines controller having capitalized pipeline name' do
expect(:get => 'api/pipelines/FOO/status').to route_to(no_layout: true, controller: 'api/pipelines', action: 'status', pipeline_name: 'FOO')
end
it 'should not route to status action of pipelines controller for invalid pipeline name' do
expect(:get => 'api/pipelines/fo$%#@6/status').to_not be_routable
end
end
end
end
describe :card_activity do
it "should generate the route" do
expect(:get => '/api/card_activity/foo.bar/10/to/15').to route_to(:controller => "api/pipelines", :action => "card_activity", :format=>"xml", :pipeline_name => 'foo.bar', :from_pipeline_counter => "10", :to_pipeline_counter => "15", "no_layout" => true)
end
it "should generate the route with show_bisect" do
expect(:get => '/api/card_activity/foo.bar/10/to/15?show_bisect=true').to route_to(:controller => "api/pipelines", :action => "card_activity", :format=>"xml", :pipeline_name => 'foo.bar', :from_pipeline_counter => "10", :to_pipeline_counter => "15", "no_layout" => true, :show_bisect => 'true')
end
it "should resolve route to itself" do
expect(:get => '/api/card_activity/foo.bar/10/to/15?show_bisect=true').to route_to(:controller => "api/pipelines", :pipeline_name=>"foo.bar", :action => "card_activity", :no_layout=>true, :from_pipeline_counter => "10", :to_pipeline_counter => "15", :format => "xml", :show_bisect => 'true')
end
it "should show_bisect when requested" do
loser = Username.new(CaseInsensitiveString.new("loser"))
controller.should_receive(:current_user).and_return(loser)
@changeset_service.should_receive(:getCardNumbersBetween).with('foo', 10, 20, loser, an_instance_of(HttpLocalizedOperationResult), true).and_return([3,5,10])
get :card_activity, :pipeline_name => 'foo', :from_pipeline_counter => "10", :to_pipeline_counter => "20", :no_layout => true, :show_bisect => 'true'
expect(response.body).to eq("3,5,10")
end
it "should return a list of cards between two pipelines" do
loser = Username.new(CaseInsensitiveString.new("loser"))
controller.should_receive(:current_user).and_return(loser)
@changeset_service.should_receive(:getCardNumbersBetween).with('foo', 10, 20, loser, an_instance_of(HttpLocalizedOperationResult), false).and_return([3,5,10])
get :card_activity, :pipeline_name => 'foo', :from_pipeline_counter => "10", :to_pipeline_counter => "20", :no_layout => true
expect(response.body).to eq("3,5,10")
end
it "should render error when there is an error" do
loser = Username.new(CaseInsensitiveString.new("loser"))
controller.should_receive(:current_user).and_return(loser)
@changeset_service.should_receive(:getCardNumbersBetween).with('foo', 10, 20, loser, an_instance_of(HttpLocalizedOperationResult), false) do |name, from, to, user, result, show_bisect|
result.notFound(LocalizedMessage.string("RESOURCE_NOT_FOUND", 'pipeline', ['foo']), HealthStateType.general(HealthStateScope.forPipeline('foo')))
end
get :card_activity, :pipeline_name => 'foo', :from_pipeline_counter => "10", :to_pipeline_counter => "20", :no_layout => true
expect(response.body).to eq("pipeline '[\"foo\"]' not found.\n")
end
describe :route do
describe :with_pipeline_name_contraint do
it 'should route to card_activity action of pipelines controller having dots in pipeline name' do
expect(:get => 'api/card_activity/some.thing/1/to/10').to route_to(no_layout: true, controller: 'api/pipelines', action: 'card_activity', pipeline_name: 'some.thing', from_pipeline_counter: '1', to_pipeline_counter: '10', format: 'xml')
end
it 'should route to card_activity action of pipelines controller having hyphen in pipeline name' do
expect(:get => 'api/card_activity/some-thing/1/to/10').to route_to(no_layout: true, controller: 'api/pipelines', action: 'card_activity', pipeline_name: 'some-thing', from_pipeline_counter: '1', to_pipeline_counter: '10', format: 'xml')
end
it 'should route to card_activity action of pipelines controller having underscore in pipeline name' do
expect(:get => 'api/card_activity/some_thing/1/to/10').to route_to(no_layout: true, controller: 'api/pipelines', action: 'card_activity', pipeline_name: 'some_thing', from_pipeline_counter: '1', to_pipeline_counter: '10', format: 'xml')
end
it 'should route to card_activity action of pipelines controller having alphanumeric pipeline name' do
expect(:get => 'api/card_activity/123foo/1/to/10').to route_to(no_layout: true, controller: 'api/pipelines', action: 'card_activity', pipeline_name: '123foo', from_pipeline_counter: '1', to_pipeline_counter: '10', format: 'xml')
end
it 'should route to card_activity action of pipelines controller having capitalized pipeline name' do
expect(:get => 'api/card_activity/FOO/1/to/10').to route_to(no_layout: true, controller: 'api/pipelines', action: 'card_activity', pipeline_name: 'FOO', from_pipeline_counter: '1', to_pipeline_counter: '10', format: 'xml')
end
it 'should not route to card_activity action of pipelines controller for invalid pipeline name' do
expect(:get => 'api/card_activity/fo$%#@6/1/to/10').to_not be_routable
end
end
describe :with_pipeline_counter_constraint do
it 'should not route to card_activity action of pipelines controller for invalid from_pipeline_counter' do
expect(:get => 'api/card_activity/some.thing/fo$%#@6/to/2').to_not be_routable
end
it 'should not route to card_activity action of pipelines controller for invalid to_pipeline_counter' do
expect(:get => 'api/card_activity/some.thing/1/to/fo$%#@6').to_not be_routable
end
end
end
end
describe :schedule do
before(:each) do
com.thoughtworks.go.server.service.result.HttpOperationResult.stub(:new).and_return(@status)
end
it "should return 404 when I try to trigger a pipeline that does not exist" do
message = "pipeline idonotexist does not exist"
@pipeline_service.should_receive(:manualProduceBuildCauseAndSave).with('idonotexist',anything(), schedule_options({}, {}), @status)
@status.stub(:httpCode).and_return(404)
@status.stub(:detailedMessage).and_return(message)
controller.should_receive(:render_if_error).with(message, 404).and_return(true)
fake_template_presence "api/pipelines/schedule.erb", "dummy"
post 'schedule', :pipeline_name => 'idonotexist', :no_layout => true
end
it "should return 404 when material does not exist" do
message = "material does not exist"
@go_config_service.should_receive(:findMaterialWithName).with(CaseInsensitiveString.new('pipeline'), CaseInsensitiveString.new('material_does_not_exist')).and_return(nil)
@pipeline_service.should_receive(:manualProduceBuildCauseAndSave).with('pipeline', anything(), schedule_options({"material_does_not_exist" => "foo"}, {}), @status)
@status.stub(:httpCode).and_return(404)
@status.stub(:detailedMessage).and_return(message)
controller.should_receive(:render_if_error).with(message, 404).and_return(true)
fake_template_presence "api/pipelines/schedule.erb", "dummy"
post 'schedule', :pipeline_name => 'pipeline', "materials" => {'material_does_not_exist' => "foo"}, :no_layout => true
end
it "should be able to specify a particular revision from a upstream pipeline" do
@go_config_service.should_receive(:findMaterialWithName).with(CaseInsensitiveString.new('downstream'), CaseInsensitiveString.new('downstream')).and_return(@material_config)
@pipeline_service.should_receive(:manualProduceBuildCauseAndSave).with('downstream',anything(), schedule_options({@fingerprint => "downstream/10/blah-stage/2"}, {}), @status)
@status.stub(:httpCode).and_return(202)
@status.stub(:detailedMessage).and_return("accepted request to schedule pipeline badger")
post 'schedule', :pipeline_name => 'downstream', "materials" => {"downstream" => "downstream/10/blah-stage/2"}, :no_layout => true
end
it "should return 202 when I trigger a pipeline successfully" do
message = "accepted request to schedule pipeline badger"
@pipeline_service.should_receive(:manualProduceBuildCauseAndSave).with('badger',anything(),schedule_options({}, {}), @status)
@status.stub(:httpCode).and_return(202)
@status.stub(:detailedMessage).and_return(message)
post 'schedule', :pipeline_name => 'badger', :no_layout => true
expect(response.response_code).to eq(202)
expect(response.body).to eq(message + "\n")
end
it "should fix empty revisions if necessary" do
@pipeline_service.should_receive(:manualProduceBuildCauseAndSave).with('downstream',anything(),schedule_options({@fingerprint => "downstream/10/blah-stage/2"}, {}), @status)
@status.stub(:httpCode).and_return(202)
@status.stub(:detailedMessage).and_return("accepted request to schedule pipeline badger")
post 'schedule', :pipeline_name => 'downstream', "materials" => {"downstream" => ""}, "original_fingerprint" => {@fingerprint => "downstream/10/blah-stage/2"}, :no_layout => true
end
it "should respect materials name material map over originalMaterials" do
svn_material_config = double('svn_material_config')
svn_fingerprint = 'svn_123456'
svn_material_config.stub(:getPipelineUniqueFingerprint).and_return(svn_fingerprint)
svn2_fingerprint = 'svn2_123456'
@go_config_service.should_receive(:findMaterialWithName).with(CaseInsensitiveString.new('downstream'), CaseInsensitiveString.new('downstream')).and_return(@material_config)
@go_config_service.should_receive(:findMaterialWithName).with(CaseInsensitiveString.new('downstream'), CaseInsensitiveString.new('svn')).and_return(svn_material_config)
@pipeline_service.should_receive(:manualProduceBuildCauseAndSave).with('downstream',anything(),schedule_options({@fingerprint => "downstream/10/blah-stage/5", svn_fingerprint => "20", svn2_fingerprint => "45"}, {}), @status)
@status.stub(:httpCode).and_return(202)
@status.stub(:detailedMessage).and_return("accepted request to schedule pipeline badger")
post 'schedule', :pipeline_name => 'downstream', "materials" => {"downstream" => "downstream/10/blah-stage/5", "svn" => "20"}, "original_fingerprint" => {@fingerprint => "downstream/10/blah-stage/2", svn_fingerprint => "30", svn2_fingerprint => "45"}, :no_layout => true
end
it "should support using pipeline unique fingerprint to select material" do
downstream = "0942094a"
svn = "875c3261"
svn_2 = "98143abd"
@pipeline_service.should_receive(:manualProduceBuildCauseAndSave).with('downstream',anything(),schedule_options({downstream => "downstream/10/blah-stage/5", svn => "20", svn_2 => "45"}, {}), @status)
@status.stub(:httpCode).and_return(202)
@status.stub(:detailedMessage).and_return("accepted request to schedule pipeline badger")
post 'schedule', :pipeline_name => 'downstream', "material_fingerprint" => {downstream => "downstream/10/blah-stage/5", svn => "20"}, "original_fingerprint" => {downstream => "downstream/10/blah-stage/2", svn => "30", svn_2 => "45"}, :no_layout => true
end
it "should support using schedule time environment variable values while scheduling a pipeline" do
downstream = "0942094a"
@pipeline_service.should_receive(:manualProduceBuildCauseAndSave).with('downstream',anything(),schedule_options({downstream => "downstream/10/blah-stage/5"}, {'foo' => 'foo_value', 'bar' => 'bar_value'}), @status)
@status.stub(:httpCode).and_return(202)
@status.stub(:detailedMessage).and_return("accepted request to schedule pipeline badger")
post 'schedule', :pipeline_name => 'downstream', "material_fingerprint" => {downstream => "downstream/10/blah-stage/5"}, 'variables' => {'foo' => 'foo_value', 'bar' => 'bar_value'}, :no_layout => true
end
it "should support using schedule time environment variable values while scheduling a pipeline" do
downstream = "0942094a"
@pipeline_service.should_receive(:manualProduceBuildCauseAndSave).with('downstream', anything(), schedule_options({downstream => "downstream/10/blah-stage/5"}, {'foo' => 'foo_value', 'bar' => 'bar_value'}, {'secure_name' => 'secure_value'}), @status)
@status.stub(:httpCode).and_return(202)
@status.stub(:detailedMessage).and_return("accepted request to schedule pipeline badger")
post 'schedule', :pipeline_name => 'downstream', "material_fingerprint" => {downstream => "downstream/10/blah-stage/5"}, 'variables' => {'foo' => 'foo_value', 'bar' => 'bar_value'}, 'secure_variables' => {'secure_name' => 'secure_value'}, :no_layout => true
end
it "should support empty material_fingerprints" do
svn = "875c3261"
@pipeline_service.should_receive(:manualProduceBuildCauseAndSave).with('downstream',anything(),schedule_options({svn => "30"}, {}), @status)
@status.stub(:httpCode).and_return(202)
@status.stub(:detailedMessage).and_return("accepted request to schedule pipeline badger")
post 'schedule', :pipeline_name => 'downstream', "material_fingerprint" => {svn => ""}, "original_fingerprint" => {svn => "30"}, :no_layout => true
end
describe :route do
describe :with_header do
before :each do
allow_any_instance_of(HeaderConstraint).to receive(:matches?).with(any_args).and_return(true)
end
describe :with_pipeline_name_constraint do
it 'should route to schedule action of pipelines controller having dots in pipeline name' do
expect(post: 'api/pipelines/some.thing/schedule').to route_to(no_layout: true, controller: 'api/pipelines', action: 'schedule', pipeline_name: 'some.thing')
end
it 'should route to schedule action of pipelines controller having hyphen in pipeline name' do
expect(post: 'api/pipelines/some-thing/schedule').to route_to(no_layout: true, controller: 'api/pipelines', action: 'schedule', pipeline_name: 'some-thing')
end
it 'should route to schedule action of pipelines controller having underscore in pipeline name' do
expect(post: 'api/pipelines/some_thing/schedule').to route_to(no_layout: true, controller: 'api/pipelines', action: 'schedule', pipeline_name: 'some_thing')
end
it 'should route to schedule action of pipelines controller having alphanumeric pipeline name' do
expect(post: 'api/pipelines/123foo/schedule').to route_to(no_layout: true, controller: 'api/pipelines', action: 'schedule', pipeline_name: '123foo')
end
it 'should route to schedule action of pipelines controller having capitalized pipeline name' do
expect(post: 'api/pipelines/FOO/schedule').to route_to(no_layout: true, controller: 'api/pipelines', action: 'schedule', pipeline_name: 'FOO')
end
it 'should not route to schedule action of pipelines controller for invalid pipeline name' do
expect(post: 'api/pipelines/fo$%#@6/schedule').to_not be_routable
end
end
end
describe :without_header do
before :each do
allow_any_instance_of(HeaderConstraint).to receive(:matches?).with(any_args).and_return(false)
end
it 'should not resolve route to schedule' do
expect(:post => "api/pipelines/foo.bar/schedule").to_not route_to(controller: "api/pipelines", pipeline_name: "foo.bar", action: "schedule", no_layout: true)
expect(post: 'api/pipelines/foo.bar/schedule').to route_to(controller: 'application', action: 'unresolved', url: 'api/pipelines/foo.bar/schedule')
end
end
end
end
describe :pipeline_instance do
it "should load pipeline by id" do
pipeline = PipelineInstanceModel.createPipeline("pipeline", 1, "label", BuildCause.createWithEmptyModifications(), stage_history_for("blah-stage"))
@pipeline_history_service.should_receive(:load).with(10, "user", anything).and_return(pipeline)
get :pipeline_instance, :id => '10', :name => "pipeline", :format => "xml", :no_layout => true
context = XmlWriterContext.new("http://test.host/go", nil, nil, nil, nil)
expect(assigns[:doc].asXML()).to eq(PipelineXmlViewModel.new(pipeline).toXml(context).asXML())
end
it "should respond with 404 when pipeline not found" do
@pipeline_history_service.should_receive(:load).with(10, "user", anything).and_return(nil) do |id, user, result|
result.notFound("Not Found", "", nil)
end
get :pipeline_instance, :id => '10', :name => "pipeline", :format => "xml", :no_layout => true
expect(response.status).to eq(404)
end
it "should respond with 401 when user does not have view permission" do
@pipeline_history_service.should_receive(:load).with(10, "user", anything).and_return(nil) do |id, user, result|
result.unauthorized("Unauthorized", "", nil)
end
get :pipeline_instance, :id => '10', :format => "xml", :name => "pipeline", :no_layout => true
expect(response.status).to eq(401)
end
it "should resolve url to action" do
expect(:get => "/api/pipelines/pipeline.com/10.xml?foo=bar").to route_to(:controller => 'api/pipelines', :action => 'pipeline_instance', :name => "pipeline.com", :id => "10", :format => "xml", :foo => "bar", :no_layout => true)
end
describe :route do
describe :with_pipeline_name_contraint do
it 'should route to pipeline_instance action of pipelines controller having dots in pipeline name' do
expect(:get => 'api/pipelines/some.thing/1.xml').to route_to(no_layout: true, format: 'xml', controller: 'api/pipelines', action: 'pipeline_instance', name: 'some.thing', id: '1')
end
it 'should route to pipeline_instance action of pipelines controller having hyphen in pipeline name' do
expect(:get => 'api/pipelines/some-thing/1.xml').to route_to(no_layout: true, format: 'xml', controller: 'api/pipelines', action: 'pipeline_instance', name: 'some-thing', id: '1')
end
it 'should route to pipeline_instance action of pipelines controller having underscore in pipeline name' do
expect(:get => 'api/pipelines/some_thing/1.xml').to route_to(no_layout: true, format: 'xml', controller: 'api/pipelines', action: 'pipeline_instance', name: 'some_thing', id: '1')
end
it 'should route to pipeline_instance action of pipelines controller having alphanumeric pipeline name' do
expect(:get => 'api/pipelines/123foo/1.xml').to route_to(no_layout: true, format: 'xml', controller: 'api/pipelines', action: 'pipeline_instance', name: '123foo', id: '1')
end
it 'should route to pipeline_instance action of pipelines controller having capitalized pipeline name' do
expect(:get => 'api/pipelines/FOO/1.xml').to route_to(no_layout: true, format: 'xml', controller: 'api/pipelines', action: 'pipeline_instance', name: 'FOO', id: '1')
end
it 'should not route to pipeline_instance action of pipelines controller for invalid pipeline name' do
expect(:get => 'api/pipelines/fo$%#@6/1.xml').to_not be_routable
end
end
end
end
describe :pipelines do
it "should assign pipeline_configs and latest instance of each pipeline configured" do
@pipeline_history_service.should_receive(:latestInstancesForConfiguredPipelines).with("user").and_return(:pipeline_instance)
get :pipelines, :format => "xml", :no_layout => true
expect(assigns[:pipelines]).to eq(:pipeline_instance)
end
describe :route do
it 'should resolve route to pipelines action' do
expect(get: 'api/pipelines.xml').to route_to(no_layout: true, format: 'xml', controller: 'api/pipelines', action: 'pipelines')
end
end
end
describe :stage_feed do
before :each do
controller.go_cache.clear
controller.stub(:set_locale)
end
it "should return the url to the feed" do
params = {:name => 'cruise'}
expect(controller.url(params)).to eq("http://test.host/api/pipelines/cruise/stages.xml")
end
it "should return the url to the page given a stage locator" do
expect(controller.page_url("cruise/1/dev/1")).to eq("http://test.host/pipelines/cruise/1/dev/1")
end
it "should answer for /api/pipelines/foo/stages.xml" do
expect(:get => '/api/pipelines/foo/stages.xml').to route_to(:controller => "api/pipelines", :action => "stage_feed", :format=>"xml", :name => 'foo', :no_layout => true)
end
it "should set the stage feed from the java side" do
Feed.should_receive(:new).with(@user, an_instance_of(PipelineStagesFeedService::PipelineStageFeedResolver), an_instance_of(HttpLocalizedOperationResult), have_key(:controller)).and_return(:stage_feed)
@go_config_service.should_receive(:hasPipelineNamed).with(CaseInsensitiveString.new('pipeline')).and_return(true)
get 'stage_feed', :format => "xml", :no_layout => true, :name => 'pipeline'
expect(assigns[:feed]).to eq(:stage_feed)
end
it "should set content type as application/atom+xml" do
Feed.should_receive(:new).with(@user, an_instance_of(PipelineStagesFeedService::PipelineStageFeedResolver), an_instance_of(HttpLocalizedOperationResult), have_key(:controller)).and_return(:stage_feed)
@go_config_service.should_receive(:hasPipelineNamed).with(CaseInsensitiveString.new('pipeline')).and_return(true)
get 'stage_feed', :format => "xml", :no_layout => true, :name => 'pipeline'
expect(response.content_type).to eq("application/atom+xml")
end
it "should honor after if present" do
Feed.should_receive(:new).with(@user, an_instance_of(PipelineStagesFeedService::PipelineStageFeedResolver), an_instance_of(HttpLocalizedOperationResult), have_key(:after)).and_return(:stage_feed)
@go_config_service.should_receive(:hasPipelineNamed).with(CaseInsensitiveString.new('pipeline')).and_return(true)
get 'stage_feed', :after => 10, :format => "xml", :no_layout => true, :name => 'pipeline'
expect(assigns[:feed]).to eq(:stage_feed)
end
it "should honor before if present" do
Feed.should_receive(:new).with(@user, an_instance_of(PipelineStagesFeedService::PipelineStageFeedResolver), an_instance_of(HttpLocalizedOperationResult), have_key(:before)).and_return(:stage_feed)
@go_config_service.should_receive(:hasPipelineNamed).with(CaseInsensitiveString.new('pipeline')).and_return(true)
get 'stage_feed', :before => 10, :format => "xml", :no_layout => true, :name => 'pipeline'
expect(assigns[:feed]).to eq(:stage_feed)
end
it "should assign title"do
Feed.should_receive(:new).with(@user, an_instance_of(PipelineStagesFeedService::PipelineStageFeedResolver), an_instance_of(HttpLocalizedOperationResult), have_key(:controller)).and_return(:stage_feed)
@go_config_service.should_receive(:hasPipelineNamed).with(CaseInsensitiveString.new('pipeline')).and_return(true)
get 'stage_feed', :format => "xml", :no_layout => true, :name => 'pipeline'
expect(assigns[:title]).to eq("pipeline")
end
it "should return stages url with before and after params" do
expected_routing_params = {:controller => "api/pipelines", :action => "stage_feed", :format => "xml", :name => 'cruise', :no_layout => true, :after => "2", :before => "bar"}
expect(:get => api_pipeline_stage_feed_path(:after => 2, :before => "bar", :name => "cruise")).to route_to(expected_routing_params)
end
it "should return 404 if the pipeline does not exist" do
controller.should_receive(:render_error_response).with("Pipeline not found", 404, true)
@go_config_service.should_receive(:hasPipelineNamed).with(CaseInsensitiveString.new('does_not_exist')).and_return(false)
get 'stage_feed', :format => "xml", :no_layout => true, :name => 'does_not_exist'
end
it "should render the error if there is any" do
Feed.should_receive(:new).with(@user, an_instance_of(PipelineStagesFeedService::PipelineStageFeedResolver), an_instance_of(HttpLocalizedOperationResult), have_key(:controller)).and_return(:stage_feed) do |a, b, c, d|
c.notFound(LocalizedMessage.string('Screwed'), HealthStateType.invalidConfig())
end
controller.should_receive(:render_localized_operation_result).with(an_instance_of(HttpLocalizedOperationResult))
@go_config_service.should_receive(:hasPipelineNamed).with(CaseInsensitiveString.new('does_not_exist')).and_return(true)
get 'stage_feed', :format => "xml", :no_layout => true, :name => 'does_not_exist'
end
describe :route do
describe :with_pipeline_name_contraint do
it 'should route to stage_feed action of pipelines controller having dots in pipeline name' do
expect(:get => 'api/pipelines/some.thing/stages.xml').to route_to(no_layout: true, format: 'xml', controller: 'api/pipelines', action: 'stage_feed', name: 'some.thing')
end
it 'should route to stage_feed action of pipelines controller having hyphen in pipeline name' do
expect(:get => 'api/pipelines/some-thing/stages.xml').to route_to(no_layout: true, format: 'xml', controller: 'api/pipelines', action: 'stage_feed', name: 'some-thing')
end
it 'should route to stage_feed action of pipelines controller having underscore in pipeline name' do
expect(:get => 'api/pipelines/some_thing/stages.xml').to route_to(no_layout: true, format: 'xml', controller: 'api/pipelines', action: 'stage_feed', name: 'some_thing')
end
it 'should route to stage_feed action of pipelines controller having alphanumeric pipeline name' do
expect(:get => 'api/pipelines/123foo/stages.xml').to route_to(no_layout: true, format: 'xml', controller: 'api/pipelines', action: 'stage_feed', name: '123foo')
end
it 'should route to stage_feed action of pipelines controller having capitalized pipeline name' do
expect(:get => 'api/pipelines/FOO/stages.xml').to route_to(no_layout: true, format: 'xml', controller: 'api/pipelines', action: 'stage_feed', name: 'FOO')
end
it 'should not route to stage_feed action of pipelines controller for invalid pipeline name' do
expect(:get => 'api/pipelines/fo$%#@6/stages.xml').to_not be_routable
end
end
end
end
describe :releaseLock do
it "should call service and render operation result" do
@pipeline_unlock_api_service.should_receive(:unlock).with('pipeline-name', @user, anything) do |name, user, operation_result|
operation_result.notAcceptable("done", HealthStateType.general(HealthStateScope::GLOBAL))
end
fake_template_presence 'api/pipelines/releaseLock.erb', 'dummy'
controller.should_receive(:render_if_error).with("done\n", 406).and_return(true)
post :releaseLock, :pipeline_name => 'pipeline-name', :no_layout => true
end
describe :route do
describe :with_header do
before :each do
allow_any_instance_of(HeaderConstraint).to receive(:matches?).with(any_args).and_return(true)
end
describe :with_pipeline_name_constraint do
it 'should route to releaseLock action of pipelines controller having dots in pipeline name' do
expect(post: 'api/pipelines/some.thing/releaseLock').to route_to(no_layout: true, controller: 'api/pipelines', action: 'releaseLock', pipeline_name: 'some.thing')
end
it 'should route to releaseLock action of pipelines controller having hyphen in pipeline name' do
expect(post: 'api/pipelines/some-thing/releaseLock').to route_to(no_layout: true, controller: 'api/pipelines', action: 'releaseLock', pipeline_name: 'some-thing')
end
it 'should route to releaseLock action of pipelines controller having underscore in pipeline name' do
expect(post: 'api/pipelines/some_thing/releaseLock').to route_to(no_layout: true, controller: 'api/pipelines', action: 'releaseLock', pipeline_name: 'some_thing')
end
it 'should route to releaseLock action of pipelines controller having alphanumeric pipeline name' do
expect(post: 'api/pipelines/123foo/releaseLock').to route_to(no_layout: true, controller: 'api/pipelines', action: 'releaseLock', pipeline_name: '123foo')
end
it 'should route to releaseLock action of pipelines controller having capitalized pipeline name' do
expect(post: 'api/pipelines/FOO/releaseLock').to route_to(no_layout: true, controller: 'api/pipelines', action: 'releaseLock', pipeline_name: 'FOO')
end
it 'should not route to releaseLock action of pipelines controller for invalid pipeline name' do
expect(post: 'api/pipelines/fo$%#@6/releaseLock').to_not be_routable
end
end
end
describe :without_header do
before :each do
allow_any_instance_of(HeaderConstraint).to receive(:matches?).with(any_args).and_return(false)
end
it 'should not resolve route to releaseLock' do
expect(:post => "api/pipelines/foo.bar/releaseLock").to_not route_to(controller: "api/pipelines", pipeline_name: "foo.bar", action: "releaseLock", no_layout: true)
expect(post: 'api/pipelines/foo.bar/releaseLock').to route_to(controller: 'application', action: 'unresolved', url: 'api/pipelines/foo.bar/releaseLock')
end
end
end
end
describe :pause do
it "should pause the pipeline" do
@pipeline_pause_service.should_receive(:pause).with("foo.bar", "wait for next checkin", Username.new(CaseInsensitiveString.new("someuser"), "Some User"), an_instance_of(HttpLocalizedOperationResult))
@controller.stub(:current_user).and_return(Username.new(CaseInsensitiveString.new("someuser"), "Some User"))
post :pause, {:pipeline_name => "foo.bar", :no_layout => true, :pauseCause => "wait for next checkin"}
end
describe :route do
describe :with_header do
before :each do
allow_any_instance_of(HeaderConstraint).to receive(:matches?).with(any_args).and_return(true)
end
describe :with_pipeline_name_constraint do
it 'should route to pause action of pipelines controller having dots in pipeline name' do
expect(post: 'api/pipelines/some.thing/pause').to route_to(no_layout: true, controller: 'api/pipelines', action: 'pause', pipeline_name: 'some.thing')
end
it 'should route to pause action of pipelines controller having hyphen in pipeline name' do
expect(post: 'api/pipelines/some-thing/pause').to route_to(no_layout: true, controller: 'api/pipelines', action: 'pause', pipeline_name: 'some-thing')
end
it 'should route to pause action of pipelines controller having underscore in pipeline name' do
expect(post: 'api/pipelines/some_thing/pause').to route_to(no_layout: true, controller: 'api/pipelines', action: 'pause', pipeline_name: 'some_thing')
end
it 'should route to pause action of pipelines controller having alphanumeric pipeline name' do
expect(post: 'api/pipelines/123foo/pause').to route_to(no_layout: true, controller: 'api/pipelines', action: 'pause', pipeline_name: '123foo')
end
it 'should route to pause action of pipelines controller having capitalized pipeline name' do
expect(post: 'api/pipelines/FOO/pause').to route_to(no_layout: true, controller: 'api/pipelines', action: 'pause', pipeline_name: 'FOO')
end
it 'should not route to pause action of pipelines controller for invalid pipeline name' do
expect(post: 'api/pipelines/fo$%#@6/pause').to_not be_routable
end
end
end
describe :without_header do
before :each do
allow_any_instance_of(HeaderConstraint).to receive(:matches?).with(any_args).and_return(false)
end
it 'should not resolve route to pause' do
expect(:post => "api/pipelines/foo.bar/pause").to_not route_to(controller: "api/pipelines", pipeline_name: "foo.bar", action: "pause", no_layout: true)
expect(post: 'api/pipelines/foo.bar/pause').to route_to(controller: 'application', action: 'unresolved', url: 'api/pipelines/foo.bar/pause')
end
end
end
end
describe :unpause do
it "should pause the pipeline" do
@pipeline_pause_service.should_receive(:unpause).with("foo.bar", Username.new(CaseInsensitiveString.new("someuser"), "Some User"), an_instance_of(HttpLocalizedOperationResult))
@controller.stub(:current_user).and_return(Username.new(CaseInsensitiveString.new("someuser"), "Some User"))
post :unpause, {:pipeline_name => "foo.bar", :no_layout => true}
end
describe :route do
describe :with_header do
before :each do
allow_any_instance_of(HeaderConstraint).to receive(:matches?).with(any_args).and_return(true)
end
describe :with_pipeline_name_constraint do
it 'should route to unpause action of pipelines controller having dots in pipeline name' do
expect(post: 'api/pipelines/some.thing/unpause').to route_to(no_layout: true, controller: 'api/pipelines', action: 'unpause', pipeline_name: 'some.thing')
end
it 'should route to unpause action of pipelines controller having hyphen in pipeline name' do
expect(post: 'api/pipelines/some-thing/unpause').to route_to(no_layout: true, controller: 'api/pipelines', action: 'unpause', pipeline_name: 'some-thing')
end
it 'should route to unpause action of pipelines controller having underscore in pipeline name' do
expect(post: 'api/pipelines/some_thing/unpause').to route_to(no_layout: true, controller: 'api/pipelines', action: 'unpause', pipeline_name: 'some_thing')
end
it 'should route to unpause action of pipelines controller having alphanumeric pipeline name' do
expect(post: 'api/pipelines/123foo/unpause').to route_to(no_layout: true, controller: 'api/pipelines', action: 'unpause', pipeline_name: '123foo')
end
it 'should route to unpause action of pipelines controller having capitalized pipeline name' do
expect(post: 'api/pipelines/FOO/unpause').to route_to(no_layout: true, controller: 'api/pipelines', action: 'unpause', pipeline_name: 'FOO')
end
it 'should not route to unpause action of pipelines controller for invalid pipeline name' do
expect(post: 'api/pipelines/fo$%#@6/unpause').to_not be_routable
end
end
end
describe :without_header do
before :each do
allow_any_instance_of(HeaderConstraint).to receive(:matches?).with(any_args).and_return(false)
end
it 'should not resolve route to unpause' do
expect(:post => "api/pipelines/foo.bar/unpause").to_not route_to(controller: "api/pipelines", pipeline_name: "foo.bar", action: "unpause", no_layout: true)
expect(post: 'api/pipelines/foo.bar/unpause').to route_to(controller: 'application', action: 'unresolved', url: 'api/pipelines/foo.bar/unpause')
end
end
end
end
end
|
require_relative 'test_helper'
require_relative '../lib/result_entry'
require_relative '../lib/result_set'
class ResultEntryTest < Minitest::Test
def test_result_set_responds_to_methods_to_access_matching_districts
rs = ResultSet.new(matching_districts: [r1], statewide_average: r2)
assert_equal 0.5, rs.matching_districts[0].free_and_reduced_price_lunch_rate
assert_equal 0.2, rs.statewide_average.children_in_poverty_rate
assert_equal 0.6, rs.statewide_average.high_school_graduation_rate
assert_nil rs.statewide_average.median_household_income
end
def r1
ResultEntry.new({free_and_reduced_price_lunch_rate: 0.5,
children_in_poverty_rate: 0.25,
high_school_graduation_rate: 0.75})
end
def r2
ResultEntry.new({free_and_reduced_price_lunch_rate: 0.3,
children_in_poverty_rate: 0.2,
high_school_graduation_rate: 0.6})
end
end
|
# frozen_string_literal: true
require_relative '../../../../test/test_helper'
describe Inferno::Sequence::USCoreR4ClinicalNotesSequence do
before do
@sequence_class = Inferno::Sequence::USCoreR4ClinicalNotesSequence
@patient_id = 1234
@docref_bundle = FHIR.from_contents(load_fixture(:clinicalnotes_docref_bundle))
@diagrpt_bundle = FHIR.from_contents(load_fixture(:clinicalnotes_diagrpt_bundle))
@instance = Inferno::TestingInstance.create(
url: 'http://www.example.com'
)
@instance.patient_id = @patient_id
@client = FHIR::Client.new(@instance.url)
end
def self.it_tests_failed_return
it 'fails with http status 4xx' do
stub_request(:get, @query_url)
.with(query: @search_params)
.to_return(
status: 400
)
error = assert_raises(Inferno::AssertionException) do
@sequence.run_test(@test)
end
assert_match(/^Bad response code/, error.message)
end
it 'fails if returned resource is not Bundle' do
stub_request(:get, @query_url)
.with(query: @search_params)
.to_return(
status: 200,
body: FHIR::DocumentReference.new.to_json
)
error = assert_raises(Inferno::AssertionException) do
@sequence.run_test(@test)
end
assert_match(/^Expected FHIR Bundle but found/, error.message)
end
it 'skips with empty bundle' do
stub_request(:get, @query_url)
.with(query: @search_params)
.to_return(
status: 200,
body: FHIR::Bundle.new.to_json
)
error = assert_raises(Inferno::SkipException) do
@sequence.run_test(@test)
end
assert_match(/^No #{@resource_class} resources with (type|category)/, error.message)
end
end
def self.it_tests_required_docref
it 'passes with correct DocumentReference in Bundle' do
code = @category_code.split('|')[1]
source = FHIR::Bundle.new
source.entry = @docref_bundle.entry.select { |item| item.resource.type.coding[0].code == code }
stub_request(:get, @query_url)
.with(query: @search_params)
.to_return(
status: 200,
body: source.to_json
)
@sequence.run_test(@test)
assert @sequence.document_attachments.attachment.keys.any?
end
end
def self.it_tests_required_diagrpt
it 'passes with correct DiagnosticReport in Bundle' do
code = @category_code.split('|')[1]
source = FHIR::Bundle.new
source.entry = @diagrpt_bundle.entry.select { |item| item.resource.category[0].coding[0].code == code }
stub_request(:get, @query_url)
.with(query: @search_params)
.to_return(
status: 200,
body: source.to_json
)
@sequence.run_test(@test)
assert @sequence.report_attachments.attachment.keys.any?
end
end
describe 'Consultation Note tests' do
before do
@sequence = @sequence_class.new(@instance, @client)
@test = @sequence_class[:have_consultation_note]
@category_code = 'http://loinc.org|11488-4'
@resource_class = 'DocumentReference'
@query_url = "#{@instance.url}/#{@resource_class}"
@search_params = { 'patient': @instance.patient_id, 'type': @category_code }
end
it_tests_failed_return
it_tests_required_docref
end
describe 'Discharge Summary tests' do
before do
@sequence = @sequence_class.new(@instance, @client)
@test = @sequence_class[:have_discharge_summary]
@category_code = 'http://loinc.org|18842-5'
@resource_class = 'DocumentReference'
@query_url = "#{@instance.url}/#{@resource_class}"
@search_params = { 'patient': @instance.patient_id, 'type': @category_code }
end
it_tests_failed_return
it_tests_required_docref
end
describe 'History and Physical Note tests' do
before do
@sequence = @sequence_class.new(@instance, @client)
@test = @sequence_class[:have_history_note]
@category_code = 'http://loinc.org|34117-2'
@resource_class = 'DocumentReference'
@query_url = "#{@instance.url}/#{@resource_class}"
@search_params = { 'patient': @instance.patient_id, 'type': @category_code }
end
it_tests_failed_return
it_tests_required_docref
end
describe 'Procedures Note tests' do
before do
@sequence = @sequence_class.new(@instance, @client)
@test = @sequence_class[:have_procedures_note]
@category_code = 'http://loinc.org|28570-0'
@resource_class = 'DocumentReference'
@query_url = "#{@instance.url}/#{@resource_class}"
@search_params = { 'patient': @instance.patient_id, 'type': @category_code }
end
it_tests_failed_return
it_tests_required_docref
end
describe 'Progress Note tests' do
before do
@sequence = @sequence_class.new(@instance, @client)
@test = @sequence_class[:have_progress_note]
@category_code = 'http://loinc.org|11506-3'
@resource_class = 'DocumentReference'
@query_url = "#{@instance.url}/#{@resource_class}"
@search_params = { 'patient': @instance.patient_id, 'type': @category_code }
end
it_tests_failed_return
it_tests_required_docref
end
describe 'Cardioogy Report tests' do
before do
@sequence = @sequence_class.new(@instance, @client)
@test = @sequence_class[:have_cardiology_report]
@category_code = 'http://loinc.org|LP29708-2'
@resource_class = 'DiagnosticReport'
@query_url = "#{@instance.url}/#{@resource_class}"
@search_params = { 'patient': @instance.patient_id, 'category': @category_code }
end
it_tests_failed_return
it_tests_required_diagrpt
end
describe 'Pathology Report tests' do
before do
@sequence = @sequence_class.new(@instance, @client)
@test = @sequence_class[:have_pathology_report]
@category_code = 'http://loinc.org|LP7839-6'
@resource_class = 'DiagnosticReport'
@query_url = "#{@instance.url}/#{@resource_class}"
@search_params = { 'patient': @instance.patient_id, 'category': @category_code }
end
it_tests_failed_return
it_tests_required_diagrpt
end
describe 'Radiology Report tests' do
before do
@sequence = @sequence_class.new(@instance, @client)
@test = @sequence_class[:have_radiology_report]
@category_code = 'http://loinc.org|LP29684-5'
@resource_class = 'DiagnosticReport'
@query_url = "#{@instance.url}/#{@resource_class}"
@search_params = { 'patient': @instance.patient_id, 'category': @category_code }
end
it_tests_failed_return
it_tests_required_diagrpt
end
describe 'Matched Attachments tests' do
before do
@sequence = @sequence_class.new(@instance, @client)
@test = @sequence_class[:have_matched_attachments]
@sequence.document_attachments = Inferno::Sequence::ClinicalNoteAttachment.new('DocumentReference')
@sequence.document_attachments.attachment['/Binary/SMART-Binary-1-note'] = 'SMART-DiagnosticReport-1-note'
@sequence.document_attachments.attachment['/Binary/SMART-Binary-2-note'] = 'SMART-DiagnosticReport-2-note'
@sequence.report_attachments = Inferno::Sequence::ClinicalNoteAttachment.new('DiagnosticReport')
@sequence.report_attachments.attachment['/Binary/SMART-Binary-1-note'] = 'SMART-DiagnosticReport-1-note'
@sequence.report_attachments.attachment['/Binary/SMART-Binary-2-note'] = 'SMART-DiagnosticReport-2-note'
end
it 'skips if skip_document_reference is true' do
@sequence.document_attachments.attachment.clear
error = assert_raises(Inferno::SkipException) do
@sequence.run_test(@test)
end
assert_match(/^There is no attachement in DocumentReference/, error.message)
end
it 'skips if report_attachments is empty' do
@sequence.report_attachments.attachment.clear
error = assert_raises(Inferno::SkipException) do
@sequence.run_test(@test)
end
assert_match(/^There is no attachement in DiagnosticReport/, error.message)
end
it 'fails if one attachment does not have a match' do
@sequence.document_attachments.attachment.delete('/Binary/SMART-Binary-2-note')
error = assert_raises(Inferno::AssertionException) do
@sequence.run_test(@test)
end
assert_equal 'Attachments /Binary/SMART-Binary-2-note in DiagnosticReport/SMART-DiagnosticReport-2-note are not referenced in any DocumentReference.', error.message
end
it 'passes if all attachments are matched' do
@sequence.run_test(@test)
end
end
end
|
class StudentApplication < ActiveRecord::Base
belongs_to :Student
has_one :app_status, :dependent => :destroy
geocoded_by :city
after_validation :geocode, :if => :city_changed?
# all fields must be filled
validates :name, :phone, :email_id, :gpa, :address, :city, :state, :country, :dob, presence: true
validates :resume, :sop, :lor, attachment_size: { less_than: 5.megabytes }
# Phone should be a number and its length should be between 10 and 15 characters
validates :phone, :numericality => true,
:length => { :minimum => 10, :maximum => 15 }
# Validate email using the regex provided by Devise
validates_format_of :email_id,:with => Devise::email_regexp, :uniqueness => true
# check if GPA lies in the correct range
validates :gpa, :numericality => { less_than_or_equal_to:4.0, greater_than_or_equal_to: 2.5 }
#validates :dob, date: { before: Date.today }
# Validate Address
# File Uploads
has_attached_file :resume
validates_attachment_content_type :resume, :content_type => %w(application/pdf)
has_attached_file :sop
validates_attachment_content_type :sop, :content_type => %w(application/pdf)
has_attached_file :lor
validates_attachment_content_type :lor, :content_type => %w(application/pdf)
end
|
require_relative 'schema'
module Schema
class DatabaseVersion < Base
self.description = "records migrations"
define(
[:id, :primary_key],
[:timestamp, :timestamp],
[:migration, :string],
[:user_id, :integer]
)
end
end
|
class Assignment < ApplicationRecord
belongs_to :lesson
validates_presence_of :lesson, :on => :create
validates_length_of :description,
:minimum => 2,
:allow_nil => true,
:allow_blank => true
validates_format_of :link,
:with => /\Ahttps?:\/\/.{0,}/,
:message => "bad format",
:allow_nil => true,
:allow_blank => true
end
|
FactoryGirl.define do
factory :intervention do
name { FFaker::Conference.name }
description { FFaker::BaconIpsum.words(30).to_sentence }
schedule { 2.days.from_now }
collective
place { "place" }
avatar_id { 'ana8sd7hfisdf' }
cover_id { 'ana8sd7hfisdf' }
end
end
|
class RemoveCountryRefFromProvinces < ActiveRecord::Migration[5.1]
def change
remove_reference :provinces, :country, foreign_key: true
end
end
|
# basic_credentials.rb
# Add basic auth credentials into Rack env.
# Return 401 Unauthorized if no credentials are passed.
require 'rack'
require 'rack/auth/abstract/handler'
require 'rack/auth/abstract/request'
module BasicCredentials
# Rack::Auth::Basic implements HTTP Basic Authentication, as per RFC 2617.
#
# Initialize with the Rack application that you want protecting,
# and a block that checks if a username and password pair are valid.
#
# See also: <tt>example/protectedlobster.rb</tt>
class Basic < Rack::Auth::AbstractHandler
def initialize(app, realm=nil, issue_challenge=true, &authenticator)
@issue_challenge = issue_challenge
super(app, realm, &authenticator)
end
def call(env)
#puts "realm: #{realm}."
auth = Basic::Request.new(env)
if @issue_challenge
return unauthorized unless auth.provided?
return bad_request unless auth.basic?
end
if auth.provided? and auth.basic?
env['REMOTE_USER'] = auth.username
env['REMOTE_PASSWORD'] = auth.password
else
env['REMOTE_USER'] = nil
env['REMOTE_PASSWORD'] = nil
end
@app.call(env)
end
private
def challenge
'Basic realm="%s"' % realm
end
class Request < Rack::Auth::AbstractRequest
def basic?
"basic" == scheme
end
def credentials
@credentials ||= params.unpack("m*").first.split(/:/, 2)
end
def username
credentials.first
end
def password
credentials.last
end
end
end
end
|
require 'set'
# @param {Integer[]} cells
# @param {Integer} n
# @return {Integer[]}
def prison_after_n_days(cells, n)
map = {}
cell_day_map = {}
set = Set.new
map[0] = cells
cell_day_map[cells] = 0
set.add(cells)
cur_day = 0
period = 0
day_rep_began = 0
cur_cell = cells
while true
cur_day += 1
cur_cell = next_day(cur_cell)
#p cur_cell
if set.include? cur_cell
day_rep_began = cell_day_map[cur_cell]
period = cur_day - day_rep_began
break
end
#p cur_day
map[cur_day] = cur_cell
cell_day_map[cur_cell] = cur_day
set.add(cur_cell)
end
final_index = (n - day_rep_began) % period + day_rep_began
#p map
map[final_index]
end
def next_day(prev_day)
res = Array.new(8) {0}
1.upto(6) do
|i|
if (prev_day[i-1] == 0 and prev_day[i+1] == 0) or (prev_day[i-1] == 1 and prev_day[i+1] == 1)
res[i] = 1
end
end
res
end
start = [1,0,0,1,0,0,1,0]
p prison_after_n_days(start, 1000000000)
=begin
note for sat july 11
make a reverse map of cell => day
figure out which day the repetition began
if repetition
period_len = cur_day - map[cur_day]
end
final_index = (N - day_rep_began) % period_len + day_rep_began
size of the cells is fixed, r rows. n can be between 1 to 10 ^ 9
so content of cells will repeat.
def next_day cur
end
day = 0
cur = start_day
set.add cur
map.add(0, start_day)
while true
day += 1
cur = next_day cur
break if set.include? cur
set.add cur
map.add(day, cur)
end
rep = day - 1
res_day = n % rep
return map.get(res_day)
=end |
require 'spec_helper'
describe "orders/new" do
before(:each) do
assign(:order, stub_model(Order,
:number => "MyString",
:email => "MyString",
:first_name => "MyString",
:last_name => "MyString",
:shopify_order_id => 1,
:total => 1.5,
:line_item_count => 1,
:financial_status => "MyString"
).as_new_record)
end
it "renders new order form" do
render
# Run the generator again with the --webrat flag if you want to use webrat matchers
assert_select "form[action=?][method=?]", orders_path, "post" do
assert_select "input#order_number[name=?]", "order[number]"
assert_select "input#order_email[name=?]", "order[email]"
assert_select "input#order_first_name[name=?]", "order[first_name]"
assert_select "input#order_last_name[name=?]", "order[last_name]"
assert_select "input#order_shopify_order_id[name=?]", "order[shopify_order_id]"
assert_select "input#order_total[name=?]", "order[total]"
assert_select "input#order_financial_status[name=?]", "order[financial_status]"
end
end
end
|
ActiveAdmin.register CreditItem do
permit_params :memo, :good_for_weeks, :quantity, :user, :user_id
includes :user
filter :user_id_equals
filter :memo
filter :quantity
filter :stripe_charge_amount
index do
selectable_column
id_column
column :memo
column :quantity
column :user
column :created_at
column :price do |credit_item|
if credit_item.stripe_charge_amount.present?
a number_to_currency(credit_item.stripe_charge_amount), href: "https://dashboard.stripe.com/payments/#{credit_item.stripe_charge_id}", target: '_blank', title: "via Stripe #{credit_item.stripe_charge_id}"
end
if credit_item.stripe_receipt_url.present?
a "receipt", href: credit_item.stripe_receipt_url, target: '_blank', title: "Stripe receipt"
end
end
actions
end
end
|
class Restaurant < ApplicationRecord
validates :name, presence: true
has_many :menus
end
|
require 'chefspec'
describe 'swap::default' do
before do
@chef_run = ChefSpec::ChefRunner.new.converge 'swap::default'
end
describe 'create the swap space' do
it 'creates swap file' do
@chef_run.should execute_command <<-EOF.gsub(/^\s{8}/, '')
dd if=/dev/zero of=/var/swapfile bs=1M count=8192
chmod 600 /var/swapfile
mkswap /var/swapfile
EOF
end
it "doesn't create swap when exists" do
pending 'TODO: Once ChefSpec supports guards'
end
end
describe 'mount' do
before do
@mount = @chef_run.mount('none')
end
it 'has correct mount point' do
@mount.name.should eql 'none'
end
it 'has correct device' do
@mount.device.should eql '/var/swapfile'
end
it 'has correct fstype' do
@mount.fstype.should eql 'swap'
end
end
describe 'activate the swap file' do
it 'runs swapon -a' do
@chef_run.should execute_command 'swapon -a'
end
it "doesn't activate the swap when activated" do
pending 'TODO: Once ChefSpec supports guards'
end
end
end
|
class Volante < ActiveRecord::Base
belongs_to :estudiante
has_attached_file :soporte
validates_attachment_content_type :soporte, :content_type => ['image/jpeg', 'image/png', 'application/pdf']
end
|
#!/usr/bin/env ruby
STDOUT.sync = true
STDERR.sync = true
require 'socket'
require 'set'
require 'getoptlong'
$default_port_number = 2345
# ================================================================
def usage()
$stderr.puts <<EOF
Usage: #{$us} [options] {workfile} {donefile}
Options:
-p {port number} Default #{$default_port_number}"
The workfile should contain work IDs, one per line. What this means is up to
the client; nominally they will be program arguments to be executed by worker
programs.
EOF
exit 1
end
# ================================================================
def main()
port_number = $default_port_number
opts = GetoptLong.new(
[ '-p', GetoptLong::REQUIRED_ARGUMENT ],
[ '-h', '--help', GetoptLong::NO_ARGUMENT ]
)
begin
opts.each do |opt, arg|
case opt
when '-p'; port_number = Integer(arg)
when '-h'; usage
when '--help'; usage
end
end
rescue GetoptLong::Error
usage
end
usage unless ARGV.length == 2
infile = ARGV.shift
donefile = ARGV.shift
server = SpitServer.new(infile, donefile, port_number)
server.server_loop
end
# ================================================================
class SpitServer
# ----------------------------------------------------------------
def initialize(infile, donefile, port_number)
@task_ids_to_do = Set.new
@task_ids_assigned = Set.new
@task_ids_done = Set.new
@task_ids_failed = Set.new
puts "#{format_time},op=read_in_file,#{format_counts}"
File.foreach(infile) do |line|
task_id = line.chomp
@task_ids_to_do << task_id
end
puts "#{format_time},op=read_done_file,#{format_counts}"
if File.exist?(donefile)
File.foreach(donefile) do |line|
task_id = line.chomp
@task_ids_done << task_id
@task_ids_to_do.delete(task_id)
end
end
@donefile = donefile
@port_number = port_number
@tcp_server = TCPServer.new(port_number)
puts "#{format_time},op=ready,port=#{port_number},#{format_counts}"
end
# ----------------------------------------------------------------
def format_time
"time=#{Time.now.to_f}"
end
def format_counts
ntodo = @task_ids_to_do.length
nassigned = @task_ids_assigned.length
ndone = @task_ids_done.length
nfailed = @task_ids_failed.length
ntotal = ntodo + nassigned + ndone + nfailed
string = "ntodo=#{ntodo}"
string += ",nassigned=#{nassigned}"
string += ",ndone=#{ndone}"
string += ",nfailed=#{nfailed}"
string += ",ntotal=#{ntotal}"
string
end
# ----------------------------------------------------------------
def server_loop
loop do
if @task_ids_to_do.length == 0
puts "#{format_time},op=exit,#{format_counts}"
# Don't break out of the loop: we're done assigning but workers are
# still running. Stay around waiting for their final mark-done messages
# to come in.
end
client = @tcp_server.accept # blocking call
handle_client(client)
client.close
end
end
# ----------------------------------------------------------------
def handle_client(client)
client_info = client.peeraddr
client_host = client_info[2]
client_port = client_info[1]
puts "#{format_time},op=accept,client=#{client_host}:#{client_port}"
line = client.gets.chomp
verb, payload = line.split(':', 2)
if verb == 'wreq'
handle_wreq(client)
elsif verb == 'show'
handle_show(client)
elsif verb == 'mark-done'
handle_mark_done(client, payload)
elsif verb == 'mark-failed'
handle_mark_failed(client, payload)
elsif verb == 'output'
handle_output(client, payload)
elsif verb == 'stats'
handle_stats(client, payload)
else
puts "#{format_time},op=drop,verb=#{verb},payload=#{payload}"
end
end
# ----------------------------------------------------------------
def handle_wreq(client)
if @task_ids_to_do.length > 0
task_id = @task_ids_to_do.first
begin
client.puts "#{task_id}"
puts "#{format_time},op=give,#{format_counts},task_id=#{task_id}"
@task_ids_assigned << task_id
@task_ids_to_do.delete(task_id)
rescue Errno::EPIPE
puts "#{format_time},op=give,exc=epipe"
end
else
begin
client.puts "no-work-left"
rescue Errno::EPIPE
end
end
end
# ----------------------------------------------------------------
def handle_show(client)
begin
client.puts "#{format_time},#{format_counts}"
rescue Errno::EPIPE
end
end
# ----------------------------------------------------------------
def handle_mark_done(client, payload)
task_id = payload
if @task_ids_assigned.include?(task_id)
@task_ids_assigned.delete(task_id)
@task_ids_done << task_id
File.open(@donefile, "a") {|handle| handle.puts(payload)}
puts "#{format_time},op=mark-done,ok=true,#{format_counts},task_id=#{payload}"
else
puts "#{format_time},op=mark-done,ok=rando,#{format_counts},task_id=#{payload}"
end
end
# ----------------------------------------------------------------
def handle_mark_failed(client, payload)
task_id = payload
if @task_ids_assigned.include?(task_id)
@task_ids_assigned.delete(task_id)
@task_ids_failed << task_id
puts "#{format_time},op=mark-failed,ok=true,#{format_counts},task_id=#{payload}"
else
puts "#{format_time},op=mark-failed,ok=rando,#{format_counts},task_id=#{payload}"
end
end
# ----------------------------------------------------------------
def handle_output(client, payload)
puts "#{format_time},op=output,#{payload}"
end
# ----------------------------------------------------------------
def handle_stats(client, payload)
puts "#{format_time},op=stats,#{payload}"
end
end
# ================================================================
main()
|
module MultitenancyTools
# {SchemaCreator} can be used to create a schema on a PostgreSQL database
# using a SQL file as template. This template should be previously generated
# by {SchemaDumper}.
#
# @example
# creator = MultitenancyTools::SchemaCreator.new('schema name', ActiveRecord::Base.connection)
# creator.create_from_file('path/to/file.sql')
class SchemaCreator
# @param schema [String] schema name
# @param connection [ActiveRecord::ConnectionAdapters::PostgreSQLAdapter] connection adapter
def initialize(schema, connection = ActiveRecord::Base.connection)
@schema = schema
@connection = connection
end
# Creates the schema using a SQL file that was generated by {SchemaDumper}.
#
# @param file [String] path to a SQL file
def create_from_file(file)
quoted_schema_name = @connection.quote_table_name(@schema)
SchemaSwitcher.new(@schema, @connection).run do
@connection.create_schema(quoted_schema_name)
@connection.execute(File.read(file))
end
end
end
end
|
require "minitest/autorun"
require_relative '../../lib/arena/circle.rb'
class Table < Minitest::Test
attr_reader :table
def setup
@table = Game::Circle.new
end
def test_invalid_move?
assert_equal true, table.invalid_move?(0,11)
end
def test_valid_move?
assert_equal false, table.invalid_move?(0,10)
end
end |
FactoryBot.define do
factory :message do
content "My team will win."
end
end
|
require 'rails_helper'
RSpec.describe BusinessesController, type: :controller do
let(:json) { JSON.parse(response.body) }
let(:user) { create(:user) }
let(:headers) { valid_headers }
let(:business_params) { attributes_for(:business) }
describe '.post' do
before do
request.headers.merge!(headers)
end
context 'when all attributes are given' do
before do
post :create, params: business_params
end
it { is_expected.to respond_with(201) }
it 'returns success message' do
expect(json['message']).to match(/Business successfully created/)
end
end
context 'when name is missing' do
before do
post :create, params: {}
end
it { is_expected.to respond_with(422) }
it 'returns failure message' do
expect(json['message'])
.to match(/Validation failed: Name can't be blank/)
end
end
end
end
|
#!/usr/bin/env ruby
# $0 --name foo200 -- simple_test.oedl --more a --foo xx@node -x
require "zlib"
require "json"
require 'optparse'
require 'base64'
require 'net/http'
$verbose = false
name = nil
uri = URI.parse('http://localhost:8002/jobs')
optparse = OptionParser.new do |opts|
opts.banner = "Usage: #{$0} [options] -- scriptFile [scriptOptions]"
opts.on('-n', '--name NAME', 'Name of experiment' ) do |n|
name = n
end
opts.on('-u', '--url URL', "URL for job service [#{uri}]" ) do |url|
uri = URI.parse(url)
end
opts.on('-v', '--verbose', "Print more information about what's going on. [#{$verbose}]" ) do |url|
$verbose = true
end
opts.on( '-h', '--help', 'Display this screen' ) do
puts opts
exit
end
end
optparse.parse!
# Next argument should be script file
unless ARGV.length >= 1
puts "ERROR: Missing script file\n"
puts optparse
abort
end
scriptFile = ARGV.shift
unless File.readable? scriptFile
puts "ERROR: Can't read script file '#{scriptFile}'"
abort
end
bc = Base64.encode64(Zlib::Deflate.deflate(File.read(scriptFile)))
script = {
type: "application/zip",
encoding: "base64",
content: bc.split("\n")
}
# Parse properties
i = 0
properties = []
while i < ARGV.length
unless (p = ARGV[i]).start_with? '-'
puts "ERROR: Script arguments need to start with '-'."
abort
end
properties << (prop = {name: p.sub(/^[\-]+/, '')})
unless (arg = ARGV[i + 1] || '').start_with? '-'
if (r = arg.split('@')).length > 1
# resource
prop[:resource] = rd = {type: (r[1] || 'node')}
rd[:name] = r[0] unless r[0].empty?
else
prop[:value] = arg unless arg.empty?
end
i += 1
end
#puts ">>> #{p} <#{arg}>"
i += 1
end
# Create default experiment name if none given
unless name
require 'etc'
require 'time'
name = "exp_#{Etc.getlogin}_#{Time.now.iso8601}"
end
job = {
name: name,
oedl_script: script,
ec_properties: properties
}
# OK, time ot post it
if $verbose
puts "Sending the following request to '#{uri}'"
puts JSON.pretty_generate(job)
end
req = Net::HTTP::Post.new(uri.path, {'Content-Type' =>'application/json'})
#req.basic_auth @user, @pass
req.body = JSON.pretty_generate(job)
response = Net::HTTP.new(uri.host, uri.port).start {|http| http.request(req) }
puts "Response #{response.code} #{response.message}:\n#{response.body}"
|
require 'spec_helper'
describe SessionsController do
describe 'POST #create' do
let(:email) { 't@gmail.com' }
let(:password) { 'password' }
let!(:user) { User.create(email: 't@gmail.com', password: 'password') }
let(:params) do
{ user: {email: email, password: 'password'} }
end
let(:email) { user.email }
before do
request.env["devise.mapping"] = Devise.mappings[:user]
EhjobAuthentication.configure do |config|
config.eh_url = 'http://www.employmenthero.com'
end
end
context 'UrlExtractorService raise errors' do
before do
expect(EhjobAuthentication::UrlExtractorService).to receive(:call).and_raise
end
context 'local user is found' do
it 'logins successfully & redirects to after_sign_in_path' do
post :create, params
expect(controller.resource).not_to be_nil
expect(response).to redirect_to '/after_sign_in_path'
end
end
context 'local user is not found' do
let(:email) {'invalid@gmail.com'}
it 'fail to login' do
post :create, params
expect(controller.resource).to be_nil
end
end
end
context 'UrlExtractorService returns nil' do
before do
expect(EhjobAuthentication::UrlExtractorService).to receive(:call).and_return nil
end
it 'logins successfully & redirects to after_sign_in_path' do
post :create, params
expect(controller.resource).not_to be_nil
expect(response).to redirect_to '/after_sign_in_path'
end
end
context 'UrlExtractorService returns url' do
before do
expect(EhjobAuthentication::UrlExtractorService).to receive(:call).and_return 'http://www.employmenthero.com'
end
it 'redirect to redirect_url' do
post :create, params
expect(response).to redirect_to 'http://www.employmenthero.com'
end
end
end
end
|
require "benchmark/ips"
require "kalculator"
Benchmark.ips do |x|
x.warmup = 2
x.time = 10
x.report("parse numbers and operators") do
Kalculator.new("5 + 8 / 3 - 1 * 4")
end
x.report("parsing names and operators") do
Kalculator.new("a + b / c - d * e")
end
x.report("parsing multi-part-names and operators") do
Kalculator.new("a.b.c + b.c.d / c.d.e - d.e.f * e.f.g")
end
end
|
Rails.application.routes.draw do
# Routes for the Feedback resource:
# CREATE
match("/new_feedback_form", { :controller => "feedbacks", :action => "blank_form", :via => "get" })
match("/insert_feedback_record", { :controller => "feedbacks", :action => "save_new_info", :via => "post" })
# READ
match("/feedbacks", { :controller => "feedbacks", :action => "list", :via => "get" })
match("/feedbacks/:id_to_display", { :controller => "feedbacks", :action => "details", :via => "get" })
# UPDATE
match("/existing_feedback_form/:id_to_prefill", { :controller => "feedbacks", :action => "prefilled_form", :via => "get" })
match("/update_feedback_record/:id_to_modify", { :controller => "feedbacks", :action => "save_edits", :via => "post" })
# DELETE
match("/delete_feedback/:id_to_remove", { :controller => "feedbacks", :action => "remove_row", :via => "get" })
#------------------------------
#LANDING PAGE route
match("/", { :controller => "restaurants", :action => "list", :via => "get" })
#compiled item reviews
match("/item_reviews/:item_id", { :controller => "reviews", :action => "item_reviews", :via => "get" })
# Routes for the Favorite resource:
# CREATE
match("/new_favorite_form", { :controller => "favorites", :action => "blank_form", :via => "get" })
match("/insert_favorite_record", { :controller => "favorites", :action => "save_new_info", :via => "post" })
# READ
match("/favorites", { :controller => "favorites", :action => "list", :via => "get" })
match("/favorites/:id_to_display", { :controller => "favorites", :action => "details", :via => "get" })
match("/user_favorites", { :controller => "favorites", :action => "user_favorites", :via => "get" })
# UPDATE
match("/existing_favorite_form/:id_to_prefill", { :controller => "favorites", :action => "prefilled_form", :via => "get" })
match("/update_favorite_record/:id_to_modify", { :controller => "favorites", :action => "save_edits", :via => "post" })
# DELETE
match("/delete_favorite/:id_to_remove", { :controller => "favorites", :action => "remove_row", :via => "get" })
#------------------------------
# Routes for the Review resource:
# CREATE
match("/new_review_form", { :controller => "reviews", :action => "blank_form", :via => "get" })
match("/insert_review_record", { :controller => "reviews", :action => "save_new_info", :via => "post" })
match("/item_review/:item_id", { :controller => "reviews", :action => "item_review", :via => "get" })
# READ
match("/reviews", { :controller => "reviews", :action => "list", :via => "get" })
match("/reviews/:id_to_display", { :controller => "reviews", :action => "details", :via => "get" })
# UPDATE
match("/existing_review_form/:id_to_prefill", { :controller => "reviews", :action => "prefilled_form", :via => "get" })
match("/update_review_record/:id_to_modify", { :controller => "reviews", :action => "save_edits", :via => "post" })
# DELETE
match("/delete_review/:id_to_remove", { :controller => "reviews", :action => "remove_row", :via => "get" })
#------------------------------
# Routes for the Item resource:
# CREATE
match("/new_item_form", { :controller => "items", :action => "blank_form", :via => "get" })
match("/insert_item_record", { :controller => "items", :action => "save_new_info", :via => "post" })
match("/insert_item_record_review", { :controller => "items", :action => "save_new_info_addreview", :via => "post" })
# READ
match("/items", { :controller => "items", :action => "list", :via => "get" })
match("/items/:id_to_display", { :controller => "items", :action => "details", :via => "get" })
# UPDATE
match("/existing_item_form/:id_to_prefill", { :controller => "items", :action => "prefilled_form", :via => "get" })
match("/update_item_record/:id_to_modify", { :controller => "items", :action => "save_edits", :via => "post" })
# DELETE
match("/delete_item/:id_to_remove", { :controller => "items", :action => "remove_row", :via => "get" })
#------------------------------
devise_for :users
#self user links
match("/my_profile", { :controller => "users", :action => "my_profile", :via => "get" })
# Routes for the Restaurant resource:
# CREATE
match("/new_restaurant_form", { :controller => "restaurants", :action => "blank_form", :via => "get" })
match("/insert_restaurant_record", { :controller => "restaurants", :action => "save_new_info", :via => "post" })
match("/insert_restaurant_record_item", { :controller => "restaurants", :action => "save_new_info_additem", :via => "post" })
# READ
match("/restaurants", { :controller => "restaurants", :action => "list", :via => "get" })
match("/restaurants/:id_to_display", { :controller => "restaurants", :action => "details", :via => "get" })
# UPDATE
match("/existing_restaurant_form/:id_to_prefill", { :controller => "restaurants", :action => "prefilled_form", :via => "get" })
match("/update_restaurant_record/:id_to_modify", { :controller => "restaurants", :action => "save_edits", :via => "post" })
# DELETE
match("/delete_restaurant/:id_to_remove", { :controller => "restaurants", :action => "remove_row", :via => "get" })
#------------------------------
devise_for :admin_users, ActiveAdmin::Devise.config
ActiveAdmin.routes(self)
# For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
end
|
# frozen_string_literal: true
require 'rails_helper'
RSpec.describe BranchesController, type: :controller do
it 'should show all branches successfully' do
branch1 = FactoryBot.create(:branch)
branch2 = FactoryBot.create(:branch)
get :index
expect(assigns(:branches)).to include branch1
expect(assigns(:branches)).to include branch2
expect(response).to have_http_status(:ok)
end
it 'has new branch' do
get :new
expect(response).to have_http_status(:ok)
end
end
|
require 'spec_helper'
describe PhotosController do
render_views
let(:valid_attributes) { { "image" => "MyString" } }
let(:valid_session) { {} }
before do
@album = Album.create! name: "The Album"
user = User.create! email: "email@foo.com", password: "password", password_confirmation: "password"
sign_in user
end
it 'shows the most recent photos' do
get :index
response.should be_successful
end
describe "POST create" do
describe "with valid params" do
it "creates a new Photo" do
expect {
post :create, {:photo => valid_attributes, album_id: @album.id}, valid_session
}.to change(Photo, :count).by(1)
Photo.last.album.should == @album
end
it "assigns a newly created photo as @photo" do
post :create, {:photo => valid_attributes, album_id: @album.id}, valid_session
assigns(:photo).should be_a(Photo)
assigns(:photo).should be_persisted
end
end
describe "with invalid params" do
it "assigns a newly created but unsaved photo as @photo" do
# Trigger the behavior that occurs when invalid params are submitted
Photo.any_instance.stub(:save).and_return(false)
post :create, {:photo => { "image" => "invalid value" }, album_id: @album.id}, valid_session
assigns(:photo).should be_a_new(Photo)
end
it "re-renders the 'index' template" do
# Trigger the behavior that occurs when invalid params are submitted
Photo.any_instance.stub(:save).and_return(false)
post :create, {:photo => { "image" => "invalid value" }, album_id: @album.id}, valid_session
response.status.should == 422
end
end
end
describe 'DELETE destroy' do
let!(:photo) { FactoryGirl.create(:photo) }
it 'allows a user to delete a product' do
request.env["HTTP_REFERER"] = "http://foo"
expect {
delete :destroy, id: photo.id
}.to change(Photo, :count).by(-1)
response.should be_redirect
end
end
end
|
Gem::Specification.new do |s|
s.name = 'machospec'
s.version = '0.0.0.1'
s.summary = 'Testing Gem'
s.description = 'Personal testing gem'
s.files = ['lib/machospec.rb']
s.require_path = 'lib'
s.test_files = ['spec/machospec_spec.rb']
s.author = 'Jose Andres Alvarez Loaiciga'
s.email = 'alvarezloaiciga@gmail.com'
s.homepage = 'https://github.com/alvarezloaiciga/machospec'
end
|
# This file is used by Rack-based servers to start the application.
# Set up gems listed in the Gemfile.
gemfile = File.expand_path('../Gemfile', __FILE__)
begin
require 'bundler'
Bundler.setup
rescue ::Bundler::GemNotFound => e
STDERR.puts e.message
STDERR.puts "Try running `bundle install`."
exit!
end if File.exist?(gemfile)
require 'pivotal_hook_service'
run PivotalHookService
|
class Scholar::ProfilesController < ScholarsController
def index
@scholars = Scholar.all
end
def show
@scholar = current_scholar
end
def edit
@scholar = current_scholar
end
def update
@scholar = current_scholar
if @scholar.update scholar_params
redirect_to scholar_profile_path @scholar.id
else
render :edit
end
end
private
def scholar_params
params.require(:scholar).permit(:group_id, :email, :password, :name)
end
end
|
class Project < ApplicationRecord
belongs_to :user, optional: true
has_many :tasks, dependent: :destroy
has_many :pus, dependent: :destroy
validates :user_id, presence: true
validates :name, presence: true, length: { minimum: 5 }
validates :description, presence: true, length: { minimum: 10 }
def self.project_by_user_project_ids(user_id, project_id)
where("id = :id AND user_id = :uid", :id => project_id, :uid => user_id)
end
end
|
class Pet < ApplicationRecord
belongs_to :shelter
has_many :pet_applications
has_many :applications, through: :pet_applications
validates_presence_of :name, :age, :sex, :description, :image
def shelter_name
shelter.name
end
def application_lookup(pet)
applications.find(pet.accepted_app_id)
end
end
|
#require "test/unit"
require 'rubygems'
require 'activesupport'
require 'active_support/test_case'
require "selenium/client"
require "selenium/client/protocol"
module Selenium::Client::Protocol
# def remote_control_command_with_symbols(*args)
# puts "Oi"
# remote_control_command_without_symbols(*args)
# puts "Oi2"
# end
#
# alias_method_chain :remote_control_command, :symbols
def click_and_wait(*locator)
click(*locator)
wait_for_page_to_load
end
def remote_control_command(verb, args=[])
args.collect! do |arg|
if arg.is_a? Symbol
SeleniumInovare::SELECTORS[arg.to_s] || raise("Selector '#{arg}' not found in /test/selenium_inovare/selectors/*.yml")
else
arg
end
end
timeout(@default_timeout_in_seconds) do
status, response = http_post(http_request_for(verb, args))
raise Selenium::CommandError, response unless status == "OK"
response
end
end
end
module SeleniumInovare
DEFAULT_SELENIUM_PARAMS = {'selenium_server_port' => 4444, 'application_server_url' => 'http://localhost:3000', 'application_server_environment' => 'development'}
SELENIUM_CONFIG_FILE = RAILS_ROOT + '/test/selenium_inovare/config.yml'
unless File.exists?(SELENIUM_CONFIG_FILE)
FileUtils.mkpath(File.dirname(SELENIUM_CONFIG_FILE))
File.open SELENIUM_CONFIG_FILE, 'w' do |f|
f.print DEFAULT_SELENIUM_PARAMS.to_yaml
end
end
PARAMS = YAML::load_file(SELENIUM_CONFIG_FILE)
SELECTORS = {}
Dir.glob(RAILS_ROOT + '/test/selenium_inovare/selectors/*.yml').each do |file|
SELECTORS.merge! YAML::load_file(file)
end
class TestCase < ActiveSupport::TestCase
@@fixtures = nil
def self.fixtures(*fixtures)
@@fixtures = fixtures
end
def link(link_description, link_href = nil)
tag = "//a[text()='#{link_description}']"
if link_href
tag << "[@href='#{link_href}']"
end
tag
end
def input(name)
"//input[@name='#{name}']"
end
def submit(value = '')
tag = "//input[@type='submit']"
unless value.blank?
tag << "[@value='#{value}']"
end
tag
end
def run(*args, &block)
return if method_name =~ /^default_test$/
begin
selenium_server_port = SeleniumInovare::PARAMS['selenium_server_port'] || raise
application_server_url = SeleniumInovare::PARAMS['application_server_url'] || raise
fixtures_environment = SeleniumInovare::PARAMS['application_server_environment'] || raise
rescue
raise "File test/selenium_inovare/config.yml has an invalid structure! If you can't fix it, delete it so it can be generated again."
end
begin
if @@fixtures
puts "Loading fixtures..."
if @@fixtures == [:all]
puts `rake db:fixtures:load RAILS_ENV=#{fixtures_environment}`
else
puts `rake db:fixtures:load RAILS_ENV=#{fixtures_environment} FIXTURES=#{ @@fixtures.join ',' }`
end
end
@browser = Selenium::Client::Driver.new \
:host => 'localhost',
:port => selenium_server_port,
:browser => "*firefox",
:url => application_server_url,
:timeout_in_second => 60
browser.start_new_browser_session
rescue Errno::ECONNREFUSED
raise "It seems that Selenium Remote Control is not running! Type 'rake selenium:rc:start' before running integration tests."
end
super
browser.close_current_browser_session
end
attr_reader :browser
end
end
|
module Metrics
module Stream
module Divergence
module Controls
module Time
def self.earlier(time=nil)
time ||= reference
Clock::UTC.iso8601(time)
end
def self.later(time=nil, divergence_milliseconds: nil)
time ||= reference
divergence_milliseconds ||= unit
time += divergence_milliseconds
Clock::UTC.iso8601(time)
end
def self.reference
::Controls::Time::Raw.example
end
def self.unit(multiple=nil)
multiple ||= 1
(multiple / 1000.0)
end
module Measurement
def self.example(time=nil)
time ||= Time.reference
end
def self.iso8601(time=nil)
time ||= example(time)
Clock::UTC.iso8601(time)
end
module Started
def self.example(time=nil)
time = Measurement.example(time) + Time.unit
end
def self.iso8601(time=nil)
time ||= example(time)
Clock::UTC.iso8601(time)
end
end
module Ended
def self.example(time=nil)
time = Measurement.example(time) + Time.unit(2)
end
def self.iso8601(time=nil)
time ||= example(time)
Clock::UTC.iso8601(time)
end
end
end
end
end
end
end
end
|
require 'menu'
describe Menu do
let(:menu) {Menu.new}
let(:dish) {double :dish}
it "should have an array for dishes" do
expect(menu.dish).to eq([])
end
it "should be able to set dish" do
menu.set(*dish)
expect(menu.dish_count).to eq(1)
end
end
|
# coding: utf-8
require_relative '../../../lib/workers/http_tool.rb'
require_relative '../../../lib/workers/sreality.rb'
class API::RequestsController < ApplicationController
respond_to :json
skip_before_action :verify_authenticity_token
#before_action :set_request, only: [:show, :edit, :update, :destroy]
def get_url_info
# test this url, it it is valid SReality url
errors = []
url = params[:url]
page_info = do_url_check(url, errors)
if page_info
total = page_info['total']
tarrif_parsed = Request.get_tarrif total
return respond_with(
{
total: total,
tarrif_parsed: tarrif_parsed,
tarrif: tarrif_parsed.join('_')
})
else
return respond_with({errors: errors}, status: 400)
end
end
# GET /requests.json
def index
@requests = Request.where('token=?', params['token'])
return respond_with(@requests)
end
# GET /requests/1
# GET /requests/1.json
#def show
# #@request = Request.find_by_token params['token']
# @request = Request.new
# respond_with @request
#end
# GET /requests/new
def new
#@request = Request.new
end
# GET /requests/1/edit
def edit
end
# POST /requests
# POST /requests.json
def create
errors = []
@request = Request.new(request_params)
page_info = do_url_check @request.url, errors
do_email_check @request.email, errors
if page_info && errors.length == 0
begin
total = page_info['total']
@request.tarrif_parsed = @request.get_tarrif total
@request.tarrif= @request.tarrif_parsed.join '_'
if @request.tarrif_parsed[1] == 'FREE'
@request.state = 'active'
end
@request.save! # save it second time to generate varsymbol
@request.varsymbol = @request.generate_varsymbol @request.id
@request.save!
unless @request.tarrif_parsed[1] != 'FREE'
# if this is not free tarrif, render SMS payment info text
#html = render_to_string("partials/_smsPay.html.erb", layout: false)
#@request.sms_guide_html = html
end
RequestNotifier.NewRequestInfo(@request).deliver
return respond_with(@request, location: nil)
rescue ActiveRecord::RecordNotUnique => e
if (e.message.include? 'index_requests_on_url_and_email')
errors << 'Sledování s touto adresou pro zadaný email je již jednou zadáno.'
return respond_with({errors: errors}, status: :unprocessable_entity, location: nil)
else
raise $!
end
end
else
return respond_with({errors: errors}, status: :unprocessable_entity)
end
end
# PATCH/PUT /requests/1
# PATCH/PUT /requests/1.json
def update
#respond_to do |format|
# if @request.update(request_params)
# format.html { redirect_to @request, notice: 'Request was successfully updated.' }
# format.json { head :no_content }
# else
# format.html { render action: 'edit' }
# format.json { render json: @request.errors, status: :unprocessable_entity }
# end
#end
end
# DELETE /requests/1
# DELETE /requests/1.json
def destroy
@request = Request.find(params[:id])
@request.destroy
respond_with()
end
private
def request_params
params.require(:request).permit(:name, :url, :email)
end
def do_url_check(url, errors)
http_tool = HttpTool.new
sreality = Sreality.new http_tool
if url !~ URI::regexp
errors << "Nesprávná url adresa, zkontrolujte, zda-li začíná znaky \"http://\""
elsif url =~ /^http:\/\/www.sreality.cz\/?$/
errors << "Nelze sledovat všechny nemovitosti, nejdříve vyberte typ nemovitosti níže - např. Prodej bytů"
elsif !sreality.is_url_valid?(url)
errors << "Nesprávná url - můžete zadat pouze adresu vedoucí na server Sreality.cz,
např. \"http://www.sreality.cz/search?category_type_cb=1&category_main_cb=1...\""
else
begin
url = sreality.set_search_page_url_age_to(url, :all)
page_info = sreality.get_page_summary(url)
unless page_info
errors << "Bohužel náš systém nebyl schopen tuto adresu zpracovat.
Chyba bude zřejmě na naší straně a nejsme schopni ji vyřešit ihned. Uložili jsme si ji a náš
team se jí bude co nejdříve zabývat."
else
return page_info
end
rescue
logger.warn 'Error when getting search page summary'
logger.warn $!
errors << 'Chybná odpověď serveru, url adresa zřejmě nebude ve správném formátu.'
end
end
return nil
end
def do_email_check(email, errors)
emailok = @request.email =~ /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\z/i
unless emailok
errors << 'Email není validní, nebo je špatném formátu.'
end
end
end |
# coding: utf-8
class Catalog::CategoryItem < ActiveRecord::Base
attr_accessible :quantity, :size, :weight, :name, :category_id
has_and_belongs_to_many :item_colors
attr_accessible :item_colors#, :item_color_ids
belongs_to :category, :inverse_of => :category_items
#images collection
has_many :category_item_images
accepts_nested_attributes_for :category_item_images#, :allow_destroy => true
attr_accessible :category_item_images_attributes#, :allow_destroy => true
# colors references
#has_and_belongs_to_many :catalog_category_item_colors
#attr_accessible :catalog_category_item_colors, :catalog_category_item_color_ids
#accepts_nested_attributes_for :category_item_colors#, :allow_destroy => true
#attr_accessible :category_item_colors_attributes#, :allow_destroy => true
def getSizeAsArray
rows = self.size.strip.split("\r\n")
@result = []
rows.each do |row|
@result << row.split('x')
end
return @result
end
rails_admin do
label 'Продукт'
label_plural 'Продукты'
list do
field :category do
label 'Категория'
end
field :name do
label 'Название продукта'
end
field :size do
label 'Размеры'
end
field :quantity do
label 'Колличество:'
end
field :weight do
label 'Вес'
end
field :category_item_images do
label 'картинки для продукта'
end
#field :category_item_colors do
# label 'цвета для продукта'
#end
end
edit do
field :category do
label 'Категория'
end
field :name do
label 'Название продукта'
end
field :size do
label 'Размеры'
end
field :quantity do
label 'Колличество: примеры:10.8 ( м2 на поддоне ); 1 ( = поштучно )'
end
field :weight do
label 'Вес'
end
field :category_item_images do
label 'картинки для продукта'
end
#field :category_item_colors do
# label 'цвета для продукта'
#end
end
end
end
|
class Outcome < ActiveRecord::Base
validates :winner, presence: true, length: { minimum: 5 }
validates :loser, presence: true, length: { minimum: 5 }
end
|
require File.expand_path(File.dirname(__FILE__) + '/spec_helper')
describe "Ip2proxy" do
it "work correctly with invalid ip" do
i2p = Ip2proxy.new.open(File.dirname(__FILE__) + "/assets/PX11.SAMPLE.BIN")
record = i2p.get_all('1.0.0.x')
expect(record['country_short']).to eq 'INVALID IP ADDRESS'
end
it "work correctly with get_all ipv4" do
i2p = Ip2proxy.new.open(File.dirname(__FILE__) + "/assets/PX11.SAMPLE.BIN")
record = i2p.get_all('1.0.0.8')
expect(record['country_short']).to eq 'US'
end
it "work correctly with get_country_short" do
i2p = Ip2proxy.new.open(File.dirname(__FILE__) + "/assets/PX11.SAMPLE.BIN")
record = i2p.get_country_short('1.0.0.8')
expect(record).to eq 'US'
end
it "work correctly with get_country_long" do
i2p = Ip2proxy.new.open(File.dirname(__FILE__) + "/assets/PX11.SAMPLE.BIN")
record = i2p.get_country_long('1.0.0.8')
expect(record).to eq 'United States of America'
end
it "work correctly with get_region" do
i2p = Ip2proxy.new.open(File.dirname(__FILE__) + "/assets/PX11.SAMPLE.BIN")
record = i2p.get_region('1.0.0.8')
expect(record).to eq 'California'
end
it "work correctly with get_city" do
i2p = Ip2proxy.new.open(File.dirname(__FILE__) + "/assets/PX11.SAMPLE.BIN")
record = i2p.get_city('1.0.0.8')
expect(record).to eq 'Los Angeles'
end
it "work correctly with get_isp" do
i2p = Ip2proxy.new.open(File.dirname(__FILE__) + "/assets/PX11.SAMPLE.BIN")
record = i2p.get_isp('1.0.0.8')
expect(record).to eq 'APNIC and CloudFlare DNS Resolver Project'
end
it "work correctly with get_domain" do
i2p = Ip2proxy.new.open(File.dirname(__FILE__) + "/assets/PX11.SAMPLE.BIN")
record = i2p.get_domain('1.0.0.8')
expect(record).to eq 'cloudflare.com'
end
it "work correctly with get_usagetype" do
i2p = Ip2proxy.new.open(File.dirname(__FILE__) + "/assets/PX11.SAMPLE.BIN")
record = i2p.get_usagetype('1.0.0.8')
expect(record).to eq 'CDN'
end
it "work correctly with get_asn" do
i2p = Ip2proxy.new.open(File.dirname(__FILE__) + "/assets/PX11.SAMPLE.BIN")
record = i2p.get_asn('1.0.0.8')
expect(record).to eq '13335'
end
it "work correctly with get_as" do
i2p = Ip2proxy.new.open(File.dirname(__FILE__) + "/assets/PX11.SAMPLE.BIN")
record = i2p.get_as('1.0.0.8')
expect(record).to eq 'CLOUDFLARENET'
end
it "work correctly with get_last_seen" do
i2p = Ip2proxy.new.open(File.dirname(__FILE__) + "/assets/PX11.SAMPLE.BIN")
record = i2p.get_last_seen('1.0.0.8')
expect(record).to eq '22'
end
it "work correctly with get_threat" do
i2p = Ip2proxy.new.open(File.dirname(__FILE__) + "/assets/PX11.SAMPLE.BIN")
record = i2p.get_threat('1.0.0.8')
expect(record).to eq '-'
end
it "work correctly with is_proxy" do
i2p = Ip2proxy.new.open(File.dirname(__FILE__) + "/assets/PX11.SAMPLE.BIN")
record = i2p.is_proxy('1.0.0.8')
expect(record).to eq 2
end
it "work correctly with get_proxytype" do
i2p = Ip2proxy.new.open(File.dirname(__FILE__) + "/assets/PX11.SAMPLE.BIN")
record = i2p.get_proxytype('1.0.0.8')
expect(record).to eq 'DCH'
end
it "work correctly with get_provider" do
i2p = Ip2proxy.new.open(File.dirname(__FILE__) + "/assets/PX11.SAMPLE.BIN")
record = i2p.get_provider('1.0.0.8')
expect(record).to eq 'CloudFlare'
end
it "work correctly with get_all ipv6" do
i2p = Ip2proxy.new.open(File.dirname(__FILE__) + "/assets/PX11.SAMPLE.BIN")
record = i2p.get_all('2c0f:ffa0::4')
expect(record['country_short']).to eq 'UG'
end
it "work correctly with get_module_version" do
i2p = Ip2proxy.new.open(File.dirname(__FILE__) + "/assets/PX11.SAMPLE.BIN")
record = i2p.get_module_version()
expect(record).to eq '3.3.0'
end
it "work correctly with get_package_version" do
i2p = Ip2proxy.new.open(File.dirname(__FILE__) + "/assets/PX11.SAMPLE.BIN")
record = i2p.get_package_version()
expect(record).to eq '11'
end
it "work correctly with get_database_version" do
i2p = Ip2proxy.new.open(File.dirname(__FILE__) + "/assets/PX11.SAMPLE.BIN")
record = i2p.get_database_version()
expect(record).to eq '2021.5.28'
end
end
|
=begin
Swagger atNuda
This is a sample atNuda server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/).
OpenAPI spec version: 1.0.0
Contact: xe314m@gmail.com
Generated by: https://github.com/swagger-api/swagger-codegen.git
=end
Rails.application.routes.draw do
def add_swagger_route http_method, path, opts = {}
full_path = path.gsub(/{(.*?)}/, ':\1')
match full_path, to: "#{opts.fetch(:controller_name)}##{opts[:action_name]}", via: http_method
end
add_swagger_route 'POST', '/portfolios/{uuid}/likes', controller_name: 'likes', action_name: 'create'
add_swagger_route 'DELETE', '/portfolios/{uuid}/likes', controller_name: 'likes', action_name: 'delete'
add_swagger_route 'POST', '/portfolios/{uuid}/comments', controller_name: 'comments', action_name: 'create'
add_swagger_route 'DELETE', '/portfolios/{uuid}/comments/{uuid}', controller_name: 'comments', action_name: 'delete_comment'
add_swagger_route 'PATCH', '/portfolios/{uuid}/comments/{uuid}', controller_name: 'comments', action_name: 'update_comment'
add_swagger_route 'POST', '/portfolios/{uuid}/corrections', controller_name: 'corrections', action_name: 'create'
add_swagger_route 'DELETE', '/portfolios/{uuid}/corrections/{uuid}', controller_name: 'corrections', action_name: 'delete_correction'
add_swagger_route 'PATCH', '/portfolios/{uuid}/corrections/{uuid}', controller_name: 'corrections', action_name: 'update_correction'
add_swagger_route 'POST', '/portfolios', controller_name: 'portfolios', action_name: 'create'
add_swagger_route 'DELETE', '/portfolios/{uuid}', controller_name: 'portfolios', action_name: 'destroy'
add_swagger_route 'GET', '/portfolios/{page}', controller_name: 'portfolios', action_name: 'show'
add_swagger_route 'PATCH', '/portfolios/{uuid}', controller_name: 'portfolios', action_name: 'update'
add_swagger_route 'POST', '/users', controller_name: 'users', action_name: 'create'
add_swagger_route 'DELETE', '/users/{uuid}', controller_name: 'users', action_name: 'destroy'
add_swagger_route 'GET', '/users/{uuid}/portfolios/{page}', controller_name: 'users', action_name: 'get_portfolios_of_user_by_uuid'
add_swagger_route 'GET', '/users/{uuid}', controller_name: 'users', action_name: 'show'
add_swagger_route 'GET', '/users', controller_name: 'users', action_name: 'index'
add_swagger_route 'PATCH', '/users/{uuid}', controller_name: 'users', action_name: 'update'
add_swagger_route 'POST', '/auth/{provider}/callback', controller_name: 'sessions', action_name: 'create'
add_swagger_route 'DELETE', '/sessions/{token}', controller_name: 'sessions', action_name: 'destroy'
add_swagger_route 'GET', '/users/{uuid}/portfolios', controller_name: 'users', action_name: 'get_user_by_uuid'
add_swagger_route 'GET', '/users/{uuid}/likes/portfolios/{page}', controller_name: 'users', action_name: 'get_likes_portfolios_of_user_by_uuid'
end
|
require "test_helper"
require "govuk-content-schema-test-helpers/test_unit"
class CalendarContentItemTest < ActiveSupport::TestCase
include GovukContentSchemaTestHelpers::TestUnit
def setup
GovukContentSchemaTestHelpers.configure do |config|
config.schema_type = "publisher_v2"
config.project_root = Rails.root
end
end
def content_item(slug: nil)
calendar = Calendar.find("bank-holidays")
CalendarContentItem.new(calendar, slug: slug)
end
def test_english_payload_contains_correct_data
payload = content_item.payload
assert_valid_against_schema payload, "calendar"
assert_equal "UK bank holidays", payload[:title]
assert_equal "en", payload[:locale]
end
def test_english_base_path_is_correct
base_path = content_item.base_path
assert_equal "/bank-holidays", base_path
end
def test_welsh_payload_contains_correct_data
payload = I18n.with_locale(:cy) { content_item.payload }
assert_valid_against_schema payload, "calendar"
assert_equal "Gwyliau banc y DU", payload[:title]
assert_equal "cy", payload[:locale]
end
def test_welsh_base_path_is_correct
base_path = I18n.with_locale(:cy) { content_item(slug: "gwyliau-banc").base_path }
assert_equal "/gwyliau-banc", base_path
end
end
|
class Item < ActiveRecord::Base
validates :name, length: { in: 1..255 }
belongs_to :list, :inverse_of => :items
end
|
class AddNewsletterFormToGlobalSettings < ActiveRecord::Migration
def change
add_column :global_settings, :newsletter_form, :text
end
end
|
# This is our step definitions file, which turns our Given, When, Then requests
# In our feature file into actionable steps using Ruby.
# For each "Given", we need a new instance of the website as the scenarios are designed
# To work independently of one another as well as collectively.
Given("I can access the Google Keep website") do
@google_keep_site_reference = Googlekeepwebsite.new
@google_keep_site_reference.google_keep_homepage.load
end
Then("I can see the Google Keep homepage") do
@google_keep_site_reference.google_keep_homepage.assertVisible
end
When("I click on the {string} link") do |string|
@google_keep_site_reference.google_keep_homepage.clickLink(string)
end
When("I click on the Web Version link") do
@google_keep_site_reference.google_keep_homepage.clickWebVersion
end
When("I login to google with a valid account") do
@google_keep_site_reference.google_log_in.assertVisible
@google_keep_site_reference.google_log_in.accessValid
end
Then("I can access the Google Keep system") do
@google_keep_site_reference.google_keep_interior.assertVisible
end
# In the below Given, we need to set up the environment to the correct state, which means repeating the work we did before.
# To allow the site to assert properly, I have added a sleep function, which tells the automation to wait for a few
# Seconds before processing the next line of code.
Given("I am already logged in to the Google Keep system") do
@google_keep_site_reference = Googlekeepwebsite.new
@google_keep_site_reference.google_keep_homepage.load
@google_keep_site_reference.google_keep_homepage.clickLink("Try Google Keep")
@google_keep_site_reference.google_keep_homepage.clickWebVersion
@google_keep_site_reference.google_log_in.assertVisible
@google_keep_site_reference.google_log_in.accessValid
sleep(5)
@google_keep_site_reference.google_keep_interior.assertVisible
end
When("I write my notes down") do
@google_keep_site_reference.google_keep_interior.writeNote
end
When("I save my note") do
@google_keep_site_reference.google_keep_interior.saveNote
end
Then("I can see my note in the list of notes.") do
@google_keep_site_reference.google_keep_interior.assertNoteVisible
end
# Thanks to the fact that we have a Given that sets up the environment, we don't need to do it again, just re-reference
# The old one above for the next steps below. This increases modularity and allows for re-usable code.
When("I have a note that can be deleted") do
@google_keep_site_reference.google_keep_interior.assertNoteVisible
end
When("I delete a note") do
@google_keep_site_reference.google_keep_interior.deleteNote
end
Then("I can no longer see my note in the list of notes.") do
sleep(5)
@google_keep_site_reference.google_keep_interior.assertNoteDeleted
end
# This is our last test, where we need to log out. Thankfully, most of this is fairly straightforward.
When("I click on the Log Out button") do
@google_keep_site_reference.google_keep_interior.logOut
end
Then("I can no longer access the Google Keep system") do
@google_keep_site_reference.google_log_in.assertVisible
end |
# "Referencia"
# Adrián Rodríguez Bazaga
require "referencia/version"
class Referencia
#Se tiene acceso de lectura y escritura a todos los atributos
attr_accessor :autores, :titulo, :serie, :editorial, :numero_edicion, :fecha_publicacion, :numeros_isbn
def initialize(autores, titulo, serie, editorial, numero_edicion, fecha_publicacion, numeros_isbn)
@autores, @titulo, @serie, @editorial, @numero_edicion, @fecha_publicacion, @numeros_isbn = autores, titulo, serie, editorial, numero_edicion, fecha_publicacion, numeros_isbn
end
def get_autores
# Devuelve el listado de autores
@autores
end
def get_titulo
# Devuelve el título
@titulo
end
def get_serie
# Devuelve la serie
@serie
end
def get_editorial
# Devuelve la editorial
@editorial
end
def get_numero_edicion
# Devuelve el número de edición
@numero_edicion
end
def get_fecha_publicacion
# Devuelve la fecha de publicación
@fecha_publicacion
end
def get_isbn
# Devuelve el listado de números ISBN
@numeros_isbn
end
def get_referencia_formateada
# Devuelve la referencia formateada (Estándar IEEE)
# Este estándar es: Autores, Titulo del libro, Edicion. Lugar de publicación: Editorial, Año de publicación.
# Omitimos 'Lugar de publicación ya que no lo tenemos'
puts "#{@autores.inspect}, #{@titulo}, #{@numero_edicion}. #{@editorial}, #{@fecha_publicacion}"
end
end
|
class CreateVersions < ActiveRecord::Migration
def change
create_table :versions do |t|
t.integer :code, null: false
t.integer :major, :minor, :point, limit: 2, null: false
t.string :file, limit: 100, null: false
t.text :description
t.string :state, limit: 50, null: false
t.timestamps null: false
end
end
end |
class AddIndexesToAssociations < ActiveRecord::Migration[6.1]
def change
# Ensure all foreign key columns for associations are indexed
add_index :contexts, :site_id
add_index :samples, :material_id
add_index :samples, :taxon_id
add_index :samples, :context_id
end
end
|
module DXYokaiWatch
class Aggregator
class Yodobashi
STOCK_CHECK_URL = 'http://www.yodobashi.com/ec/product/stock/100000001002065181/index.html?popup=1'
PRODUCT_PAGE_URL = 'http://www.yodobashi.com/%E3%83%90%E3%83%B3%E3%83%80%E3%82%A4-%E5%A6%96%E6%80%AA%E3%82%A6%E3%82%A9%E3%83%83%E3%83%81-DX%E5%A6%96%E6%80%AA%E3%82%A6%E3%82%A9%E3%83%83%E3%83%81-%E8%85%95%E6%99%82%E8%A8%88%E5%9E%8B%E7%8E%A9%E5%85%B7/pd/100000001002065181/'
def self.aggregator
@aggregator ||= []
@aggregator[0] ||= DXYokaiWatch::HTMLFetcher.new(STOCK_CHECK_URL)
@aggregator[1] ||= DXYokaiWatch::HTMLFetcher.new(PRODUCT_PAGE_URL)
@aggregator
end
def self.get_stock_information
stock_check = aggregator[0].parsed_html()
img_url_nokogiri = stock_check.css('div.pImg > img').first
img_url = img_url_nokogiri ? img_url_nokogiri['src'] : nil
product_page = aggregator[1].parsed_html()
price = product_page.css('strong#js_scl_unitPrice').text
price = price.empty? ? nil : price.gsub(/[^\d]/, '').to_i
stock_information = stock_check.css('div.storeInfoUnit').map do |elm|
store_url_nokogiri = elm.css('a').first
store_url = store_url_nokogiri ? store_url_nokogiri['href'] : PRODUCT_PAGE_URL
{
img_url: img_url,
store_name: 'ヨドバシカメラ ' + elm.css('div.storeName').text,
store_url: store_url,
price: price,
stocked: elm.css('span.uiIconTxtS').text == '在庫なし' ? false : true,
}
end
stock_information.reverse
end
end
end
end
|
class Employers::EmployersController < ApplicationController
layout "employers/employer"
before_action :authenticate_user!
before_action :current_ability
load_and_authorize_resource
before_action :load_company
private
def load_company
@company = current_user.companies.last
return if @company
flash[:danger] = t "can_not_find_company"
redirect_to root_path
end
end
|
# -*- encoding : utf-8 -*-
class AddRoleToMembers < ActiveRecord::Migration
def change
add_column :members, :role, :string, :default => 'član'
end
end
|
class CreateDoctors < ActiveRecord::Migration
def change
create_table :doctors do |t|
t.string :name
t.string :email
t.string :room
t.string :officeno
t.string :cellno
t.integer :arrivaltime
t.integer :leavetime
t.timestamps null: false
end
end
end
|
require 'rails_helper'
RSpec.describe Song, type: :model do
it 'is valid with title' do
song = Song.create(title: "Moose song", chart: 'moose_song.txt')
expect(song).to be_valid
end
it 'is valid with a chart' do
song = Song.create(title: "Moose song", chart: 'moose_song.txt')
expect(song).to be_valid
end
it 'is invalid without a title' do
song = Song.create(title: nil, chart: 'moose_song.txt')
expect(song).to_not be_valid
end
it 'is invalid without a chart' do
song = Song.create(title: 'Earth Cup', chart: nil)
expect(song).to_not be_valid
end
it 'can have the same name as another song' do
song = Song.create(title: "Juice", chart: "juice.txt")
song2 = Song.new(title: "Juice", chart: "juice.txt")
expect(song2).to be_valid
end
end
|
require 'spec_helper'
describe Society::Node do
let(:node) { Society::Node.new(
name: "Foo",
address: "./foo.rb",
edges: %w{Bar Bat}
)
}
describe "#initialize" do
it "assigns its name" do
expect(node.name).to eq("Foo")
end
it "assigns its address" do
expect(node.address).to eq("./foo.rb")
end
it "assigns its edges" do
expect(node.edges).to eq(["Bar", "Bat"])
end
end
describe "#edge_count" do
it "returns a count of its edges" do
expect(node.edge_count).to eq 2
end
end
end |
require 'forwardable'
class Game
extend Forwardable
attr_reader :players, :current_player
def_delegator :player1, :name, :player1_name
def_delegator :player1, :hit_points, :player1_hit_points
def_delegator :player2, :name, :player2_name
def_delegator :player2, :hit_points, :player2_hit_points
def_delegator :current_player, :name, :current_player_name
def initialize(player1, player2)
@players = [player1, player2]
@current_player = player1
end
def player1
players.first
end
def player2
players.last
end
def attack
opposite_player.reduce_points
end
def switch_player
@current_player = opposite_player
end
private
def opposite_player
@current_player == player1 ? player2 : player1
end
end
|
class Acs::Request
attr_accessor :q, :k, :n, :f, :t
def initialize(params)
if params[:q].blank? && params[:k].blank?
raise Acs::QOrKRequired, "You gotta say :q or :k"
end
if !params[:q].blank? && !params[:k].blank?
raise Acs::DoubleQuery, "You have provided a query and ids. Which did you intend?"
end
end
end |
class ToolPhotoSerializer < ActiveModel::Serializer
attributes :id, :tool_id, :url
end
|
class CommentsController < BaseController
before_action :authenticate_user!, only: [:new, :create, :update, :destroy]
def new
@comment = Comment.new
@post = Post.find(params[:post_id])
@category = Category.find(params[:category_id])
end
def create
@post = Post.find(params[:post_id])
@category = Category.find(params[:category_id])
if params[:comment][:parent_id].to_i > 0
parent = Comment.find_by_id(params[:comment].delete(:parent_id))
@comment = parent.children.build(comment_params.merge(user_id: current_user.id, post_id: params[:post_id] ))
else
@comment = Comment.new(comment_params.merge(user_id: current_user.id, post_id: params[:post_id]))
end
if @comment.save
flash[:success] = 'Su comentario fue agregado!'
respond_with([@category, @post])
else
render 'new'
end
end
def edit
@comment = Comment.find(params[:id])
end
def update
@comment = Comment.find(params[:id])
respond_to do |format|
if @comment.update_attributes(body: params[:body])
format.json { head :no_content }
else
end
end
end
def destroy
comment = Comment.find(params[:id])
@post = Post.find(params[:post_id])
@category = Category.find(params[:category_id])
flash[:notice] = 'El comentario fue eliminado!' if comment.destroy
respond_with([@category, @post])
end
private
def comment_params
permitted_params.permit
end
end
|
module AdvancedSearchFilterTimestamp
def self.call(resource_class)
if resource_class.respond_to?(:folder_name)
filename = File.join(Rails.root, 'app', 'views', 'people', resource_class.folder_name, 'advanced_search_filters.json.jbuilder')
else
filename = File.join(Rails.root, 'app', 'views', resource_class.downcase.pluralize, 'advanced_search_filters.json.jbuilder')
end
File.mtime(filename).to_i
end
end
|
# frozen_string_literal: true
require 'dry/transaction'
module IndieLand
module Service
# Analyzes contributions to a project
# :reek:InstanceVariableAssumption
# :reek:TooManyStatements
# :reek:UncommunicativeVariableName
# :reek:FeatureEnvy
# :reek:DuplicateMethodCall
# :reek:UtilityFunction
class Tickets
include Dry::Transaction
step :find_events_from_kktix_api
step :write_back_to_ticket_database
private
KKTIX_API_ERR = "Error occurs at fetching Kktix's api"
WRITE_TICKET_DB_ERR = 'Error occurs at writing tickets back to the database'
def find_events_from_kktix_api(input)
input[:logger].info('Getting tickets from the kktix api')
tickets = MinistryOfCulture::TicketsMapper.new.find_tickets
Success(tickets: tickets, logger: input[:logger])
rescue StandardError => e
input[:logger].error(e.backtrace.join("\n"))
Failure(Response::ApiResult.new(status: :internal_error, message: KKTIX_API_ERR))
end
def write_back_to_ticket_database(input)
input[:logger].info('Writting tickets back to the database')
Repository::For.entity(input[:tickets][0]).create_many(input[:tickets])
Success(logger: input[:logger])
rescue StandardError => e
input[:logger].error(e.backtrace.join("\n"))
Failure(Response::ApiResult.new(status: :internal_error, message: WRITE_TICKET_DB_ERR))
end
end
end
end
|
class DaysController < ApplicationController
before_action :signed_in_user
def create
@user = current_user
@day = current_user.days.build(day_params)
if @day.save
flash[:successs] = "シフト登録完了"
redirect_to @user
else
render 'static_pages/home'
end
end
def destroy
@user = current_user
Day.find(params[:id]).destroy
flash[:success] = " シフトは削除されました"
redirect_to @user
end
private
def day_params
params.require(:day).permit(:date, :time,:wage)
end
end |
module Refinery
module Businesses
class Business < Refinery::Core::BaseModel
self.table_name = 'refinery_businesses'
attr_accessible :name, :description, :position, :website, :phone, :street, :city, :state, :area, :category, :photo_id
acts_as_indexed :fields => [:name, :website, :phone, :street, :city, :state, :area, :category]
validates :name, :presence => true, :uniqueness => true
belongs_to :photo, :class_name => '::Refinery::Image'
end
end
end
|
class CreateDependentCards < ActiveRecord::Migration[5.2]
def change
create_table :dependent_cards do |t|
t.string :name_of_dependent
t.string :dependent_type
t.date :date_of_birth
t.date :date_of_issue
t.integer :personel_detail_id
t.timestamps
end
end
end
|
class ChangesSkillsInProjects < ActiveRecord::Migration[5.2]
def change
rename_column :projects, :skills, :technologies
end
end
|
class HomeController < ApplicationController
def index
@stocks = current_lab ? current_lab.stocks : []
end
def generate_xls
Axlsx::Package.new do |p|
p.workbook.add_worksheet(:name => "Pie Chart") do |sheet|
sheet.add_row ["Simple Pie Chart"]
%w(first second third).each { |label| sheet.add_row [label, rand(24)+1] }
sheet.add_chart(Axlsx::Pie3DChart, :start_at => [0,5], :end_at => [10, 20], :title => "example 3: Pie Chart") do |chart|
chart.add_series :data => sheet["B2:B4"], :labels => sheet["A2:A4"], :colors => ['FF0000', '00FF00', '0000FF']
end
end
send_data p.to_stream.read, type: "application/xlsx", filename: "filename.xlsx"
end
end
end
|
module CourierFacility
class ParkingSlot
# Has slot
attr_accessor :id, :parcel_id
@@parking_slots = {}
def initialize(args)
@id = args[:id]
@parcel_id = args[:parcel_id]
end
def self.create(size)
1.upto(size).each do |id|
slot = new(id: id)
all_by_id[id] = slot
end
all_by_id.size
end
def self.allocate_nearest_parking_slot(parcel_id)
available_slot_id = nearest_available_parking_slot_id
if available_slot_id.nil?
raise ::CourierFacility::Error.new(self), 'Sorry, parcel slot is full'
else
all_by_id[available_slot_id].parcel_id = parcel_id
return "Allocated slot number: #{available_slot_id}"
end
end
def self.available_parking_slots
@@parking_slots.select { |id, obj| obj.parcel_id.nil? }
end
def self.deliver(id)
slot = all_by_id[id]
if slot.nil?
raise ::CourierFacility::Error.new(self), "Invalid slot number #{id}!"
end
if slot.parcel_id.nil?
raise ::CourierFacility::Error.new(self), "Slot number #{id} is already free!"
else
slot.parcel_id = nil
return "Slot number #{id} is free"
end
end
def self.status
status_message = "Slot No\t\tRegistration No\t\tWeight\n"
parcels_by_id = get_parcels_by_id
all_by_id.each do |id, slot|
if slot.parcel_id.nil?
status_message.concat("#{id}\t\tNA\t\t\tNA\n")
else
parcel = parcels_by_id[slot.parcel_id]
status_message.concat("#{id}\t\t#{parcel.code}\t\t\t#{parcel.weight}\n")
end
end
status_message
end
def self.slots_with_parcel_id(parcel_id)
slot_ids = []
all_by_id.each do |id, slot|
slot_parcel_id = slot.parcel_id
next if slot_parcel_id.nil?
slot_ids.push(id) if slot_parcel_id == parcel_id
end
slot_ids
end
def self.slots_with_parcel_weight(weight)
slot_ids = []
parcel_ids = get_parcel_codes_with_weight(weight)
all_by_id.each do |id, slot|
slot_parcel_id = slot.parcel_id
next if slot_parcel_id.nil?
slot_ids.push(id) if parcel_ids.include?(slot_parcel_id)
end
slot_ids
end
private
def self.nearest_available_parking_slot_id
nearest_available_slot_id = nil
allocation_order.each do |slot_1, slot_2|
if slot_available?(slot_1)
nearest_available_slot_id = slot_1
break
elsif slot_available?(slot_2)
nearest_available_slot_id = slot_2
break
end
end
nearest_available_slot_id
end
def self.all_by_id
@@parking_slots
end
def self.slot_available?(id)
all_by_id[id].parcel_id.nil?
end
def self.parking_slots_count
all_by_id.size
end
def self.allocation_order
order = []
1.upto(parking_slots_count/2).each do |slot_no|
order.push([slot_no, nearest_slot(slot_no)])
end
order
end
def self.nearest_slot(given_slot)
parking_slots_count - given_slot + 1
end
def self.get_parcels_by_id
::CourierFacility::Parcel.all_by_code
end
def self.get_parcel_codes_with_weight(weight)
::CourierFacility::Parcel.parcel_codes_with_weight(weight)
end
end
end
|
require "test_helper"
# rubocop:disable all
class ContactMessageMailerTest < ActionMailer::TestCase
test "contact_me" do
message = ContactMessage.new name: "anna",
email: "anna@example.org",
body: "hello, how are you doing?"
email = ContactMailer.contact_me(message)
assert_emails 1 do
email.deliver_now
end
assert_equal "Contact de anna@example.org", email.subject
assert_match /hello, how are you doing?/, email.body.encoded
end
end
# rubocop:enable all
|
class MonitoringSession < ActiveRecord::Base
include MonitoringSessionHelper
enum session_state: [:open,:close]
has_many :pings
end
|
class AddParkIdToTrail < ActiveRecord::Migration[5.0]
def change
add_column :trails, :park_id, :integer
end
end
|
require 'cucumber-api/response'
require 'rest-client'
require 'json-schema'
require 'jsonpath'
if ENV['cucumber_api_verbose'] == 'true'
RestClient.log = 'stdout'
end
Given(/^I send and accept JSON$/) do
@headers = {
:Accept => 'application/json',
:'Cookie' => '',
:'Content-Type' => 'application/json'
}
end
Given(/^I'm already logged in as "(.*)"$/) do |username|
steps %Q{
When I send and accept JSON
}
file = File.read("./features/examples/authenticate.json")
login = JSON.parse(file)
login['params']['db'] = "demo4"
login['params']['login'] = username
@body = JSON.generate(login)
steps %Q{
When I send a POST request to "/app_api/session/authenticate/"
Then the response status should be "200"
Then the JSON response should follow "features/schemas/authenticate_response.schema.json"
Then the JSON response should have key "$.result.username" with "#{username}"
When I grab "$.result.session_id" as "session"
}
@headers[:Cookie] = "session_id=#{@grabbed["session"]}"
end
When(/^I set request body from "(.*)"$/) do |filename|
path = %-#{Dir.pwd}/#{filename}-
@body = File.read(path)
end
When(/^I grab "(.*?)" as "(.*?)"$/) do |json_path, place_holder|
if @response.nil?
raise 'No response found, a request need to be made first before you can grab response'
end
@grabbed = {} if @grabbed.nil?
@grabbed[%/#{place_holder}/] = @response.get json_path
end
When(/^I send a POST request to "(.*?)" with:$/) do |url, table|
table = table.raw
table.each do |row|
@grabbed.each do |key, value|
row[1] = value if row[1] == %-{#{key}}-
end
@body = JsonPath.for(@body).gsub(row[0]) {|v| row[1] }.to_hash
end
@body = JSON.generate(@body)
request_url = URI.encode (host + url)
begin
response = RestClient.post request_url, @body, @headers
rescue RestClient::Exception => e
response = e.response
end
@response = CucumberApi::Response.create response
save_request
save_response
@body = nil
@grabbed = nil
end
When(/^I send a POST request to "(.*?)"$/) do |url|
request_url = URI.encode (host + url)
begin
response = RestClient.post request_url, @body, @headers
rescue RestClient::Exception => e
response = e.response
end
@response = CucumberApi::Response.create response
save_request
save_response
@body = nil
@grabbed = nil
end
Then(/^the response status should be "(\d+)"$/) do |status_code|
expect(@response.code).to eq(status_code.to_i)
end
Then(/^the JSON response should follow "(.*?)"$/) do |schema|
file_path = %-#{Dir.pwd}/#{schema}-
expect(JSON::Validator.validate!(file_path, @response.to_s)).to be true
end
Then(/^the JSON response should have key "(.*?)" with "(.*?)"$/) do |json_path, value|
expect((@response.get json_path).to_s).to eq value
end
def save_response
timestamp = Time.now.to_i.to_s
@scenario_name = @scenario_name.gsub(/\//,'-')
File.open("responses/#{@scenario_name}-#{@step_count}-#{timestamp}.json",'w') do |f|
f.puts YAML.dump(@response.headers)
f.puts ''
f.puts @response.to_json_s
end
puts 'responses/' + @scenario_name + '-' + @step_count.to_s + '-' + timestamp + '.json'
end
def save_request
timestamp = Time.now.to_i.to_s
@scenario_name = @scenario_name.gsub(/\//,'-')
File.open("requests/#{@scenario_name}-#{@step_count}-#{timestamp}.json",'w') do |f|
f.puts YAML.dump(@headers)
f.puts ''
f.puts @body
end
puts 'requests/' + @scenario_name + '-' + @step_count.to_s + '-' + timestamp + '.json'
end |
require 'test_helper'
require 'test_helper_functions'
class RailsSourceTest < Minitest::Test
include TestHelperFunctions
def setup
define_test_values
prepare_file_tests
@values_folder = File.join(@tmp_test_data, "rails")
@target = "rails"
end
def teardown
clear_file_tests
end
def test_rails_source_import
@text_db = Pompeu::TextDB.new
rails_source = Pompeu::RailsSource.new @text_db, @languages, @values_folder, @target
rails_source.import_all
assert @text_db.find_text @target, ["some", "key", "text1"]
assert_equal "some text", translation(["some", "key", "text1"], "en").text
assert_equal "another text", translation(["some", "key", "text2"], "en").text
end
def test_rails_source_import_and_export
text_db = Pompeu::TextDB.new
rails_source = Pompeu::RailsSource.new text_db, @languages, @values_folder, @target
rails_source.import_all
rails_source2 = Pompeu::RailsSource.new text_db, @languages, @outfolder, @target
rails_source2.export
assert_empty diff_dirs(@values_folder, @outfolder)
end
def translation key, language
@text_db.find_text(@target, key).translation(language)
end
end
|
# == Schema Information
#
# Table name: users
#
# id :integer not null, primary key
# name :string
# email :string
# created_at :datetime not null
# updated_at :datetime not null
# encrypted_password :string
# salt :string
# admin :boolean default(FALSE)
#
require 'rails_helper'
RSpec.describe User, type: :model do
#user = User.create!(:name => "Alex Arzola", :email => "alex@alex.com", :password => "alex123", :password_confirmation => "alex123")
before(:each) do
@attr = {:name => "Alex Arzola",
:email => "alex@alex.com",
:password => "alex123",
:password_confirmation => "alex123"}
end
it "should create a new instance given a valid attribute" do
User.create(@attr)
end
it "should require a name" do
no_name_user = User.new(@attr.merge(:name => ""))
expect(no_name_user).to_not be_valid
end
it "should require an email address" do
no_email_user = User.new(@attr.merge(:email => ""))
expect(no_email_user).to_not be_valid
end
it "should reject names that are too long" do
long_name = "address" * 51
long_name_user = User.new(@attr.merge(:name => long_name))
expect(long_name_user).to_not be_valid
end
it "should accept valid email addresses" do
addresses = %w[user@foo.com THE_USER@foo.bar.org first.last@foo.co.jp]
addresses.each do |address|
#valid_email_user = User.new(@attr.merge(:email => address))
valid_email_user = create(:user, :email => address)
expect(valid_email_user).to be_valid
end
end
it "should reject invalid email addresses" do
addresses = %w[user@foo,com user_at_foo.org first.last@foo.]
addresses.each do |address|
invalid_email_user = User.new(@attr.merge(:email => address))
expect(invalid_email_user).to_not be_valid
end
end
it "should reject duplicate email addresses" do
#User.create!(@attr)
user = create(:user)
#user_with_duplicate_email = User.new(@attr)
user_with_duplicate_email = User.new(@attr.merge(:email => user.email))
expect(user_with_duplicate_email).to_not be_valid
end
it "should reject email addresses identical up to case" do
upcased_email = @attr[:email].upcase
#User.create!(@attr)
user = create(:user, :email => @attr[:email])
user_with_duplicate_email = User.new(@attr.merge(:email => upcased_email))
expect(user_with_duplicate_email).to_not be_valid
end
describe "passwords" do
before(:each) do
@user = User.new(@attr)
end
it "should have a password attribute" do
expect(@user).to respond_to(:password)
end
it "should have a password confirmation attribute" do
expect(@user).to respond_to(:password_confirmation)
end
end
describe "passwords validation" do
it "should require a password" do
user = User.new(@attr.merge(:password => "", :password_confirmation => ""))
expect(user).to_not be_valid
end
it "should require a matching password confirmation" do
invalid_user = User.new(@attr.merge(:password_confirmation => "invalid"))
expect(invalid_user).to_not be_valid
end
it "should reject short passwords" do
short = "a" * 5
hash = @attr.merge(:password => short, :password_confirmation => short)
expect(User.new(hash)).to_not be_valid
end
it "should reject long passwords" do
long = "a" * 41
hash = @attr.merge(:password => long, :password_confirmation => long)
expect(User.new(hash)).to_not be_valid
end
end
describe "password encryption" do
before(:each) do
#@user = User.create(@attr)
@user = create(:user)
end
it "should have an encrypted password attribute" do
expect(@user).to respond_to (:encrypted_password)
end
it "should set the encrypted password attributes" do
expect(@user.encrypted_password).to_not be_blank
end
it "should have a salt" do
expect(@user).to respond_to(:salt)
end
describe "has_password?" do
it "should exit" do
expect(@user).to respond_to (:has_password?)
end
it "should return true if the passwords match" do
expect(@user.has_password?(@attr[:password])).to be true
end
it "should return false if the passwords don't match'" do
expect(@user.has_password?("invalid")).to be false
end
end
describe "authenticaion method" do
it "should exist" do
expect(User).to respond_to(:authenticate)
end
it "should return nil on email/password mismatch" do
expect(User.authenticate(@attr[:email], "wrong password")).to be nil
end
it "should return nil for an email address with no user" do
expect(User.authenticate("bar@foo.com", @attr[:password])).to be nil
end
it "should return the user on email/password match" do
#expect(User.authenticate(@attr[:email], @attr[:password])).to eq @user
expect(User.authenticate(@user.email, @user.password)).to eq @user
end
end
end
describe "admin attribute" do
before(:each) do
#@user = User.create!(@attr)
@user = create(:user)
end
it "should resopnd to admin attribute" do
expect(@user).to respond_to(:admin)
end
it "should not be an admin by default" do
expect(@user).to_not be_admin
end
it "should be convertible to an admin" do
@user.toggle!(:admin)
expect(@user).to be_admin
end
end
describe "microposts associations" do
before(:each) do
@user = create(:user)
@mp1 = create(:micropost, :user => @user, :created_at => 1.day.ago)
@mp2 = create(:micropost, :user => @user, :created_at => 1.hour.ago)
end
it "should have a micropost attribute" do
expect(@user).to respond_to(:microposts)
end
it "should have the right microposts in the right order" do
expect(@user.microposts).to eq [@mp2, @mp1]
end
it "should destroy associated microposts" do
@user.destroy
[@mp1, @mp2].each do |micropost|
#expect(Micropost.find_by_id(micropost.id)).to be nil
expect { Micropost.find(micropost)}.to raise_error(ActiveRecord::RecordNotFound)
end
end
describe "status feed" do
# before(:each) do
# @new_user = create(:user, :email => generate(:email))
# @user.follow!(@new_user)
# end
it "should have a feed" do
expect(@user).to respond_to(:feed)
end
it "should include user's microposts" do
#expect(@user.feed.include?(@mp1)).to be true
expect(@user.feed).to include(@mp1)
expect(@user.feed).to include(@mp2)
end
it "should not include a different user's microposts" do
#user = create(:user, :email => generate(:email))
#mp3 = create(:micropost, :user => user , :content => "aoogah!")
#expect(@user.feed).to_not include(mp3)
mp3 = create(:micropost, :user => create(:user, :email => generate(:email)))
expect(@user.feed).to_not include(mp3)
end
it "should include the microposts from following users" do
following = create(:user, :email => generate(:email))
mp3 = create(:micropost, :user => following)
@user.follow!(following)
expect(@user.feed).to include(mp3 )
end
end
end
describe "relationships" do
#followed == following
before(:each) do
@user = User.create!(@attr)
@following = create(:user)
end
it "should have a relationships method" do
expect(@user).to respond_to(:relationships)
end
it "should have a following method" do
expect(@user).to respond_to(:following)
end
it "should follow another user" do
@user.follow!(@following)
expect(@user).to be_following(@following)
end
it "should include the following user in the user.following array" do
@user.follow!(@following)
expect(@user.following).to include(@following)
end
it "should have an unfollow! method" do
expect(@user).to respond_to(:unfollow!)
end
it "should unfollow a user" do
@user.follow!(@following)
@user.unfollow!(@following)
expect(@user).to_not be_following(@following)
end
it "should have a reverse_relationships method" do
expect(@user).to respond_to(:reverse_relationships)
end
it "should have a followers method" do
expect(@user).to respond_to(:followers)
end
it "should include the follower in the followers array" do
@user.follow!(@following)
expect(@following.followers).to include(@user)
end
end
end |
class Api::V1::UsersController < ApplicationController
skip_before_action :verify_authenticity_token
def sign_up
begin
form_data = decode_jwt(params[:token])
create_user(form_data)
render json: {state: 'SUCCESS'}
rescue => exception
render json: { state: 'FAILED', error: exception }
end
end
def sign_in
begin
form_data = decode_jwt(params[:token])
user = fetch_user(form_data)
authenticate_user(form_data, user)
rescue => exception
render json: { state: 'FAILED', error: exception }
end
end
private
def create_user(form_data)
email = form_data["email"]
password = form_data["password"]
crypt = generate_crypt
encrypted_pwd = crypt.encrypt_and_sign(password)
User.create!(email: email, password: encrypted_pwd)
end
def fetch_user(form_data)
email = form_data["email"]
user = User.find_by_email(email)
end
def authenticate_user(form_data, user)
password = form_data["password"]
crypt = generate_crypt
decrypt = crypt.decrypt_and_verify(user.password)
if password == decrypt
token = generate_session_token(user)
render json: {state: 'SUCCESS', token: token.token, id: user.id}
else
render json: {state: 'FAILED', error: 'Password Mismatch'}
end
end
def generate_session_token(user)
UserValidationToken.create!(token: SecureRandom.alphanumeric(10), user: user)
end
end
|
class Api::V1::DevicesController < Api::V1::ApiController
def create
device = current_user.devices.find_or_create_by(device_params)
render json: device, status: :created
end
private
def device_params
params.permit(:token, :platform)
end
end
|
# Filters added to this controller apply to all controllers in the application.
# Likewise, all the methods added will be available for all controllers.
class ApplicationController < ActionController::Base
include AuthenticatedSystem
helper :all # include all helpers, all the time
helper_method :current_account, :calendar
protect_from_forgery # See ActionController::RequestForgeryProtection for details
# Scrub sensitive parameters from your log
filter_parameter_logging :password
before_filter :subdomains_allowed?
before_filter :account_exists?
before_filter :subdomain_logged_in?
before_filter :set_locale
before_filter :set_timezone
before_filter :set_calendar
layout 'application', :except => [:rss, :xml, :json, :atom, :vcf, :xls, :csv, :pdf]
def subdomains_allowed?
# Overwritten in descendant classes if required.
end
def account_exists?
Account.find_by_name!(account_subdomain) if request_has_subdomains?
end
def subdomain_logged_in?
if request_has_subdomains? && !logged_in? && !login_controller?
store_location
flash[:notice] = 'must_login'
redirect_to login_path
end
end
# Prededence:
# => :lang parameter, if it can be matched with an available locale
# => locale in the user profile, if they're logged in
# => priority locale from the Accept-Language header of the request
# => The default site locale
def set_locale
language = params.delete(:lang)
locale = I18n.available_locales & [language] if language
locale = current_user.locale if logged_in? && !locale
locale ||= request.preferred_language_from(I18n.available_locales)
I18n.locale = locale || I18n.default_locale
end
def set_timezone
Time.zone = logged_in? ? current_user.timezone : browser_timezone
end
def set_calendar
@calendar = (current_account ? current_account.calendar : Calendar.gregorian)
end
def calendar
@calendar
end
def current_account
current_user.account if current_user
end
def request_has_subdomains?
request.subdomains.size > 0
end
# First subdomain is the account name. Note that this relies
# on prefiltering the wwww subdomain in the web server or dns
def account_subdomain
request.subdomains.first
end
def login_controller?
params[:controller] == "sessions"
end
# The browsers give the # of minutes that a local time needs to add to
# make it UTC, while TimeZone expects offsets in seconds to add to
# a UTC to make it local.
def browser_timezone
return nil if cookies[:tzoffset].blank?
@browser_timezone = begin
cookies[:tzoffset].to_i.hours
end
@browser_timezone
end
def users_ip_address
request.env["HTTP_X_REAL_IP"] || request.remote_addr || request.remote_ip
end
def browser
request.env["HTTP_USER_AGENT"]
end
def protect_against_forgery?
if request.xhr?
false
else
super
end
end
end
|
# question_7.rb
def foo(param = "no")
"yes"
end
def bar(param = "no")
param == "no" ? "yes" : "no"
end
bar(foo)
# The output of this code would be "no". foo returns "yes" regardless of what parameter (if any)
# is passed to it. "yes" is passed to bar and since "yes" does not equate to "no" (i.e. param == "no"
# evaluates to false) then "no" is returned by the ternary operator
|
require 'rails_helper'
RSpec.describe User, type: :model do
describe '新規登録' do
before do
@user = FactoryBot.build(:user)
end
context '新規登録できるとき' do
it 'passwordが6文字以上であれば登録できること' do
@user.password = 'a12345'
@user.password_confirmation = 'a12345'
expect(@user).to be_valid
end
end
context '登録できないとき' do
it 'nicknameが空では登録できないこと' do
@user.nickname = ''
@user.valid?
expect(@user.errors.full_messages).to include("ニックネームを入力してください")
end
it 'emailが空では登録できないこと' do
@user.email = ''
@user.valid?
expect(@user.errors.full_messages).to include("Eメールを入力してください")
end
it '重複したemailが存在する場合登録できないこと' do
@user.save
another_user = FactoryBot.build(:user, email: @user.email)
another_user.valid?
expect(another_user.errors.full_messages).to include('Eメールはすでに存在します')
end
it 'emailに@を含まなければ登録できないこと' do
@user.email = 'test.com'
@user.valid?
expect(@user.errors.full_messages).to include('Eメールは不正な値です')
end
it 'passwordが空では登録できないこと' do
@user.password = ''
@user.valid?
expect(@user.errors.full_messages).to include("パスワードを入力してください")
end
it 'passwordが5文字以下であれば登録できないこと' do
@user.password = '12345'
@user.password_confirmation = '12345'
@user.valid?
expect(@user.errors.full_messages).to include("パスワードは6文字以上で入力してください")
end
it 'passwordが半角英数字混合でなければ登録できないこと' do
@user.password = 'aaaaaa'
@user.valid?
expect(@user.errors.full_messages).to include("パスワードは半角英数字で入力してください")
end
it 'passwordが半角英数字混合でなければ登録できないこと' do
@user.password = '123456'
@user.valid?
expect(@user.errors.full_messages).to include("パスワードは半角英数字で入力してください")
end
it 'passwordとpassword_confirmationが不一致では登録できないこと' do
@user.password = '123456'
@user.password_confirmation = '1234567'
@user.valid?
expect(@user.errors.full_messages).to include("パスワード(確認用)とパスワードの入力が一致しません")
end
it 'first_nameが空では登録できないこと' do
@user.first_name = ''
@user.valid?
expect(@user.errors.full_messages).to include("名前を入力してください")
end
it 'first_nameが全角入力でなければ登録できないこと' do
@user.first_name = 'テスト'
@user.valid?
expect(@user.errors.full_messages).to include('名前は全角で入力してください')
end
it 'last_nameが空では登録できないこと' do
@user.last_name = ''
@user.valid?
expect(@user.errors.full_messages).to include('名字を入力してください')
end
it 'last_nameが全角入力でなければ登録できないこと' do
@user.last_name = 'テスト'
@user.valid?
expect(@user.errors.full_messages).to include('名字は全角で入力してください')
end
it 'first_name_kanaが空では登録できないこと' do
@user.first_name_kana = ''
@user.valid?
expect(@user.errors.full_messages).to include("名前(カナ)を入力してください")
end
it 'first_name_kanaが全角カタカナでないと登録できないこと' do
@user.first_name_kana = 'テスト'
@user.valid?
expect(@user.errors.full_messages).to include('名前(カナ)は全角で入力してください')
end
it 'last_name_kanaが空では登録できないこと' do
@user.last_name_kana = ''
@user.valid?
expect(@user.errors.full_messages).to include("名字(カナ)を入力してください")
end
it 'last_name_kanaが全角カタカナでないと登録できないこと' do
@user.last_name_kana = 'テスト'
@user.valid?
expect(@user.errors.full_messages).to include('名字(カナ)は全角で入力してください')
end
it 'birthdayが空では登録できないこと' do
@user.birthday = ''
@user.valid?
expect(@user.errors.full_messages).to include("生年月日を入力してください")
end
end
end
end
|
require "find"
module ETL
class TDriveCrawler
# Given a list of subjects (or a tag?) and file type?
# gets matching list of files for each subject
T_DRIVE_ROOT = "/home/pwm4/Windows/tdrive/IPM"
FILE_TYPE_LIST = {
dbf: {
new_forms: {source_type_id: 10022, pattern: /.*NewForms.*\.dbf\z/i}
},
sh: {
}
}
## TEST FUNCTION
def self.gather_stats
stats = {}
subjects_in_list = []
bad_sc = []
subjects_rejected = []
Find.find('/home/pwm4/Windows/tdrive/IPM') do |f|
if FILE_TYPE_LIST[:dbf][:new_forms][:pattern].match f
sc_match = Regexp.new("\\/" + Subject::SUBJECT_CODE_REGEX.source + "\\/", true).match f
if sc_match
if SubjectGroup.find_by_name("authorized").subjects.find_by_subject_code(sc_match[1])
stats[sc_match[1]] ||= {count: 0, file_names: []}
stats[sc_match[1]][:file_names] << f
stats[sc_match[1]][:count] += 1
subjects_in_list << sc_match[1]
else
subjects_rejected << sc_match[1]
end
else
MY_LOG.error "!!!!!!: #{f}"
bad_sc << f
end
end
end
MY_LOG.info stats.to_yaml
MY_LOG.info "found: (#{subjects_in_list.uniq.length}) #{subjects_in_list.uniq}"
MY_LOG.info "rejected: (#{subjects_rejected.uniq.length}) #{subjects_rejected.uniq}"
MY_LOG.info "number of bad sc: #{bad_sc.length}"
end
def self.get_file_list(type, name, subject_group = nil, root_path = T_DRIVE_ROOT)
file_list = {}
subjects_rejected = []
bad_subject_code = []
match_count = 0
subject_list = subject_group ? subject_group.subjects : Subject.current
#source_type = SourceType.find(FILE_TYPE_LIST[type][name][:source_type_id])
LOAD_LOG.info "##### Searching for Subject Files #####"
Find.find(root_path) do |f|
#MY_LOG.info "SEARCHING DIR: #{f}" if /.*IPM\/[^\/]*\/[^\/]*\z/i.match f
if FILE_TYPE_LIST[type][name][:pattern].match f
match_count += 1
sc_match = Regexp.new("\\/" + Subject::SUBJECT_CODE_REGEX.source + "\\/", true).match f
if sc_match
# Subject Code folder found in file path
subject_code = sc_match[1]
if subject_list.find_by_subject_code(subject_code)
# Subject in list of subjects to be loaded
LOAD_LOG.info "Adding #{subject_code}!"
file_list[subject_code] ||= []
file_list[subject_code] << f
else
subjects_rejected << subject_code
end
else
# No clear subject code folder found in file path. TODO: Add functionality to account for a wider range of folder names
# For these files, maybe suggest a subject code by looking inside the file.
bad_subject_code << f
end
LOAD_LOG.info "Searched through #{match_count} matches so far..." if match_count % 100 == 0
end
end
#LOAD_LOG.info "\nSubject Group: '#{subject_group_name}'\nFile Type: #{type} - #{name}\nSource Type: #{source_type.name}"
LOAD_LOG.info "Subjects with at least one file found (#{file_list.keys.length}): #{file_list.keys}"
LOAD_LOG.info "Subjects not in desired group (#{subjects_rejected.uniq.length}): #{subjects_rejected.uniq}"
LOAD_LOG.info "No Subject Folder found (#{bad_subject_code.length}): #{bad_subject_code}"
LOAD_LOG.info "#######################################"
file_list
end
def self.understand_dbf(file_list)
details = {}
file_list.each do |subject_code, dbf_files|
details[subject_code] ||= {}
details[subject_code][:file_count] = dbf_files.length
details[subject_code][:file_details] = []
details[subject_code][:sc_match] = true
dbf_files.each do |dbf_file_path|
dbf_reader = ETL::DbfReader.open(dbf_file_path)
details[subject_code][:file_details] << {
name: File.basename(dbf_file_path),
row_count: dbf_reader.length,
columns: dbf_reader.columns,
first_labtime: dbf_reader.row_index("LABTIME").present? ? dbf_reader.contents.first[dbf_reader.row_index("LABTIME")] : nil,
last_labtime: dbf_reader.row_index("LABTIME").present? ? dbf_reader.contents.last[dbf_reader.row_index("LABTIME")] : nil,
subject_code: dbf_reader.row_index("SUBJECT").present? ? dbf_reader.contents.first[dbf_reader.row_index("SUBJECT")] : nil
}
details[subject_code][:sc_match] = details[subject_code][:sc_match] ? details[subject_code][:file_details].last[:subject_code] == subject_code : details[subject_code][:sc_match]
dbf_reader.close
end
end
details
end
def self.find_subject_directory(subject, root_path = T_DRIVE_ROOT, search_t_drive)
subject_dirs = []
# Add all possible variations of t drive location
if subject.t_drive_location.present?
t_drive_dir_transformed = self.standardize_location(subject.t_drive_location)
if File.basename(subject.t_drive_location).upcase == subject.subject_code
subject_dirs << subject.t_drive_location
subject_dirs << t_drive_dir_transformed
elsif File.basename(subject.t_drive_location) =~ /#{subject.subject_code}/i
MY_LOG.info "WARNING: UNCONVENTIONAL T DRIVE LOCATION: #{subject.t_drive_location}"
subject_dirs << subject.t_drive_location
subject_dirs << t_drive_dir_transformed
else
subject_dirs << File.join(subject.t_drive_location, subject.subject_code)
subject_dirs << File.join(subject.t_drive_location, subject.subject_code.downcase)
subject_dirs << File.join(t_drive_dir_transformed, subject.subject_code)
subject_dirs << File.join(t_drive_dir_transformed, subject.subject_code.downcase)
end
#MY_LOG.info "#{subject.t_drive_location} | #{t_drive_dir_transformed} | #{subject_dirs} | #{subject_dirs.uniq.keep_if { |d| File.directory? d }}"
subject_dirs = subject_dirs.uniq.keep_if do |d|
# Checks if directory is part of directory list of it's parent folder
# Replaced just File.directory? d since that did not account for capitalization differences
File.directory?(d) && Dir[File.dirname(d)+"/*"].include?(d)
end
end
# If folder cannot be found using t drive location, search T drive
if subject_dirs.empty? and search_t_drive
Find.find(root_path) do |path|
if FileTest.directory?(path)
if File.basename(path).upcase == subject.subject_code
subject_dirs << path
Find.prune
end
end
end
end
# What if more than one folder is found?
raise StandardError, "Error with: #{subject_dirs}" if subject_dirs.length > 1
subject_dirs.first
end
def self.populate_t_drive_location(subject_group, root_path = T_DRIVE_ROOT)
subject_codes = subject_group.subjects.map(&:subject_code)
t_drive_loc_map = {}
subject_codes.each {|sc| t_drive_loc_map[sc] = []}
results = {none_found: [], locations_differ: [], locations_same: [], new_set: [], multiple_found: []}
start = Time.now
Find.find(root_path) do |path|
if FileTest.directory?(path)
if Time.now - start > 60
start = Time.now
LOAD_LOG.info "current path: #{path} results: #{results}"
end
possible_subject_code = File.basename(path.upcase)
if possible_subject_code =~ Subject::SUBJECT_CODE_REGEX && subject_codes.include?(possible_subject_code)
t_drive_loc_map[possible_subject_code] << path
Find.prune
end
end
end
t_drive_loc_map.each_pair do |sc, locations|
if locations.length == 0
LOAD_LOG.info "No T drive location found for subject #{sc}!"
results[:none_found] << sc
elsif locations.length == 1
s = Subject.find_by_subject_code sc
new_location = locations.first
if s.t_drive_location.present?
if new_location != self.standardize_location(s.t_drive_location)
LOAD_LOG.info "Warning!! For subject #{sc}, T drive location found (#{new_location}) is different than current T drive location (#{s.t_drive_location}. No change will be made."
results[:locations_differ] << sc
else
LOAD_LOG.info "For subject #{sc}, found T drive location is the same as current location. No change will be made."
results[:locations_same] << sc
end
else
LOAD_LOG.info "The following T drive locations is being set for subject #{sc}: #{new_location}."
s.update_attribute(:t_drive_location, new_location)
results[:new_set] << sc
end
else
LOAD_LOG.info "Warning!! Multiple locations found for subject #{sc}: #{locations}"
results[:multiple_found] << sc
end
end
results
end
private
def self.standardize_location(loc)
loc.gsub(/(^\w)/, '/\1').gsub(':', '')
end
end
end
|
# -*- encoding: utf-8 -*-
Gem::Specification.new do |s|
s.name = %q{tomcat-rails}
s.version = "0.1.2"
s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version=
s.authors = ["David Calavera"]
s.date = %q{2009-06-14}
s.default_executable = %q{tomcat_rails}
s.email = %q{david.calavera@gmail.com}
s.executables = ["tomcat_rails"]
s.extra_rdoc_files = [
"LICENSE",
"README.rdoc"
]
s.files = [
".document",
".gitignore",
"History.txt",
"LICENSE",
"README.rdoc",
"Rakefile",
"TODO.txt",
"VERSION",
"bin/tomcat_rails",
"lib/tomcat-rails.rb",
"lib/tomcat-rails/command_line_parser.rb",
"lib/tomcat-rails/jars.rb",
"lib/tomcat-rails/server.rb",
"lib/tomcat-rails/web_app.rb",
"spec/spec.opts",
"spec/spec_helper.rb",
"spec/tomcat-rails/command_line_parser_spec.rb",
"spec/tomcat-rails/web_app_spec.rb",
"spec/web_app_mock/classes/HelloTomcat.class",
"spec/web_app_mock/lib/jyaml-1.3.jar",
"spec/web_app_mock/tomcat.yml",
"tomcat-libs/core-3.1.1.jar",
"tomcat-libs/jasper-el.jar",
"tomcat-libs/jasper-jdt.jar",
"tomcat-libs/jasper.jar",
"tomcat-libs/jetty-util-6.1.14.jar",
"tomcat-libs/jruby-rack-0.9.4.jar",
"tomcat-libs/jsp-2.1.jar",
"tomcat-libs/jsp-api-2.1.jar",
"tomcat-libs/servlet-api-2.5-6.1.14.jar",
"tomcat-libs/tomcat-core.jar",
"tomcat-libs/tomcat-dbcp.jar",
"tomcat-libs/tomcat-jasper.jar",
"tomcat-rails.gemspec"
]
s.has_rdoc = true
s.homepage = %q{http://github.com/calavera/tomcat-rails}
s.rdoc_options = ["--charset=UTF-8"]
s.require_paths = ["lib"]
s.rubygems_version = %q{1.3.2}
s.summary = %q{Simple library to run a rails application into an embed Tomcat}
s.test_files = [
"spec/spec_helper.rb",
"spec/tomcat-rails/command_line_parser_spec.rb",
"spec/tomcat-rails/web_app_spec.rb"
]
if s.respond_to? :specification_version then
current_version = Gem::Specification::CURRENT_SPECIFICATION_VERSION
s.specification_version = 3
if Gem::Version.new(Gem::RubyGemsVersion) >= Gem::Version.new('1.2.0') then
else
end
else
end
end
|
require 'test_helper'
class MediaAttachmentsControllerTest < ActionController::TestCase
setup do
@media_attachment = media_attachments(:one)
end
test "should get index" do
get :index
assert_response :success
assert_not_nil assigns(:media_attachments)
end
test "should get new" do
get :new
assert_response :success
end
test "should create media_attachment" do
assert_difference('MediaAttachment.count') do
post :create, media_attachment: { link: @media_attachment.link, matrix_entry_id: @media_attachment.matrix_entry_id, title: @media_attachment.title, type: @media_attachment.type }
end
assert_redirected_to media_attachment_path(assigns(:media_attachment))
end
test "should show media_attachment" do
get :show, id: @media_attachment
assert_response :success
end
test "should get edit" do
get :edit, id: @media_attachment
assert_response :success
end
test "should update media_attachment" do
patch :update, id: @media_attachment, media_attachment: { link: @media_attachment.link, matrix_entry_id: @media_attachment.matrix_entry_id, title: @media_attachment.title, type: @media_attachment.type }
assert_redirected_to media_attachment_path(assigns(:media_attachment))
end
test "should destroy media_attachment" do
assert_difference('MediaAttachment.count', -1) do
delete :destroy, id: @media_attachment
end
assert_redirected_to media_attachments_path
end
end
|
class Asset < ActiveRecord::Base
# SCOPES
scope :cover, -> { where(cover: true) }
# ASSOCIATIONS
belongs_to :assetable, polymorphic: true
# MACROS
mount_uploader :asset, AssetUploader
include Rails.application.routes.url_helpers
# INSTANCE METHODS
def alt_name
asset.file.filename.split('.').first.gsub(/[_,-]/, ' ')
end
end
|
class DeliveryArea < ApplicationRecord
belongs_to :purchase_record
end
|
class Cospul < ApplicationRecord
Gutentag::ActiveRecord.call self
scope :new_posts , -> { order(created_at: :desc)}
scope :post_includes , -> { includes(:user,:likes,:cospul_pictures,:taggings,:tags )}
scope :set_page , -> (page){ page(page).per(9)}
def tags_as_string
tag_names.join(', ')
end
def tags_as_string=(string)
self.tag_names = string.split(/,\s*/)
end
belongs_to :user
has_many :likes , dependent: :destroy
has_many :liking_users , through: :likes , source: :user
has_one :cospul_detail , dependent: :destroy
has_many :cospul_pictures , dependent: :destroy
accepts_nested_attributes_for :cospul_pictures , allow_destroy: true, reject_if: :all_blank
has_many :gutentag_taggings ,dependent: :destroy,foreign_key: :taggable_id
has_many :gutentag_tags , through: :gutentag_taggings
validates :title , presence: true, length: { in: 1..40 }
validates :content , presence: true, length: { maximum: 1000 }
validates :user , presence: true
validates :cospul_pictures , presence: true
end
|
require "helpers/integration_test_helper"
# TODO: this is a port over from legacy tests. It shouldn't be scoped under Google, but under Google::Shared.
class TestAuthentication < FogIntegrationTest
def setup
@google_json_key_location = Fog.credentials[:google_json_key_location]
@google_json_key_string = File.open(File.expand_path(@google_json_key_location), "rb", &:read)
end
def test_authenticates_with_json_key_location
c = Fog::Compute::Google.new(:google_key_location => nil,
:google_key_string => nil,
:google_json_key_location => @google_json_key_location,
:google_json_key_string => nil)
assert_kind_of(Fog::Compute::Google::Real, c)
end
def test_authenticates_with_json_key_string
c = Fog::Compute::Google.new(:google_key_location => nil,
:google_key_string => nil,
:google_json_key_location => nil,
:google_json_key_string => @google_json_key_string)
assert_kind_of(Fog::Compute::Google::Real, c)
end
def test_raises_argument_error_when_google_project_is_missing
assert_raises(ArgumentError) { Fog::Compute::Google.new(:google_project => nil) }
end
def test_raises_argument_error_when_google_keys_are_given
assert_raises(ArgumentError) do
Fog::Compute::Google.new(:google_key_location => nil,
:google_key_string => nil,
:google_json_key_location => nil,
:google_json_key_string => nil)
end
end
end
|
BOX_IMAGE = "generic/ubuntu1604"
SETUP_MASTER = true
SETUP_NODES = true
NODE_COUNT = 2
MASTER_IP = "192.168.26.10"
NODE_IP_NW = "192.168.26."
#NODE_IP_NW = "192.168.122."
POD_NW_CIDR = "10.244.0.0/16"
#Generate new using steps in README
KUBETOKEN = "b029ee.968a33e8d8e6bb0d"
$kubeminionscript = <<MINIONSCRIPT
sudo swapoff -a
kubeadm reset -f
kubeadm join --discovery-token-unsafe-skip-ca-verification --token #{KUBETOKEN} #{MASTER_IP}:6443
sudo apt-get install -y nfs-common
sudo echo "192.168.26.10:/ /mnt nfs4 _netdev,auto 0 0" >> /etc/fstab
sudo mount -a
# Disable swap permanently
sudo sed -i '/ swap / s/^/#/' /etc/fstab
MINIONSCRIPT
$kubemasterscript = <<SCRIPT
sudo swapoff -a
kubeadm reset -f
kubeadm init --kubernetes-version v1.18.0 --apiserver-advertise-address=#{MASTER_IP} --pod-network-cidr=#{POD_NW_CIDR} --token #{KUBETOKEN} --token-ttl 0
mkdir -p $HOME/.kube
sudo cp -Rf /etc/kubernetes/admin.conf $HOME/.kube/config
sudo chown $(id -u):$(id -g) $HOME/.kube/config
# Flannel installation
sudo sysctl net.bridge.bridge-nf-call-iptables=1
kubectl apply -f /vagrant/kube-flannel_kvm.yml
# Intall Canal
kubectl apply -f https://docs.projectcalico.org/manifests/canal.yaml
# Share NFS
sudo mkdir -p /storage/dynamic
sudo chmod -R 755 /storage
sudo apt-get install -y nfs-kernel-server
sudo mkdir /shared
sudo chmod 755 /shared
sudo echo "/shared 192.168.26.0/24(rw,no_root_squash)" >> /etc/exports
sudo systemctl unmask idmapd
sudo exportfs -a
sudo service nfs-kernel-server restart
sudo service idmapd restart
# Dashboard installation
kubectl apply -f https://raw.githubusercontent.com/kubernetes/dashboard/v2.0.0/aio/deploy/recommended.yaml
kubectl create clusterrolebinding dashboard-admin-sa --clusterrole=cluster-admin --serviceaccount=default:dashboard-admin-sa
kubectl create serviceaccount dashboard-admin-sa
kubectl config set-credentials kubernetes-admin --token="$(kubectl -n default describe secret dashboard-admin-sa | awk '$1=="token:"{print $2}')"
# Disable swap permanently
sudo sed -i '/ swap / s/^/#/' /etc/fstab
cp $HOME/.kube/config /vagrant/kubeconfig.yaml
SCRIPT
Vagrant.configure("2") do |config|
config.vm.box = BOX_IMAGE
config.vm.box_check_update = false
config.vm.provider "virtualbox" do |l|
l.cpus = 1
l.memory = "1024"
end
config.vm.provision :shell, :path => "scripts/enable_swap_limit_support.sh"
config.vm.provision :reload
config.vm.provision :shell, :path => "scripts/provision_software.sh"
config.hostmanager.enabled = true
config.hostmanager.manage_guest = true
# config.vm.network "public_network"
if SETUP_MASTER
config.vm.define "master" do |subconfig|
subconfig.vm.hostname = "master"
subconfig.vm.network :private_network, ip: MASTER_IP
subconfig.vm.provider :virtualbox do |vb|
vb.customize ["modifyvm", :id, "--cpus", "2"]
vb.customize ["modifyvm", :id, "--memory", "2048"]
vb.customize ["modifyvm", :id, "--graphicscontroller", "vmsvga"]
vb.name = "master"
vb.vm.provision :shell, inline: "kubectl apply -f /vagrant/kube-flannel_virtualbox.yml"
end
subconfig.vm.provider :kvm do |kv|
kv.vm.provision :shell, inline: "kubectl apply -f /vagrant/kube-flannel_kvm.yml"
end
subconfig.vm.synced_folder ".", "/vagrant", type: "nfs", disabled: false
subconfig.vm.provision :shell, inline: $kubemasterscript
subconfig.vm.provision :shell, :path => "scripts/install_on_cluster.sh"
subconfig.vm.synced_folder "../../..", "/usr/src/git_repo", type: "nfs"
end
end
if SETUP_NODES
(1..NODE_COUNT).each do |i|
config.vm.define "node#{i}" do |subconfig|
subconfig.vm.hostname = "node#{i}"
subconfig.vm.synced_folder ".", "/vagrant", type: "nfs", disabled: false
subconfig.vm.network :private_network, ip: NODE_IP_NW + "#{i + 10}"
subconfig.vm.provision :shell, inline: $kubeminionscript
subconfig.vm.provider :virtualbox do |vb|
vb.customize ["modifyvm", :id, "--graphicscontroller", "vmsvga"]
vb.name = "node#{i}"
end
end
end
end
end |
require 'goby'
RSpec.describe Array do
context "nonempty?" do
it "returns true when the array contains elements" do
expect([1].nonempty?).to be true
expect(["Hello"].nonempty?).to be true
expect([false, false].nonempty?).to be true
end
it "returns false when the array contains no elements" do
expect([].nonempty?).to be false
expect(Array.new.nonempty?).to be false
end
end
end
RSpec.describe Integer do
context "is positive?" do
it "returns true for an integer value that is greater than zero" do
expect(0.positive?).to be false
expect(1.positive?).to be true
expect(-1.positive?).to be false
end
end
context "is nonpositive?" do
it "returns true for an integer value less than or equal to zero" do
expect(0.nonpositive?).to be true
expect(1.nonpositive?).to be false
expect(-1.nonpositive?).to be true
end
end
context "is negative?" do
it "returns true for an integer value less than zero" do
expect(0.negative?).to be false
expect(1.negative?).to be false
expect(-1.negative?).to be true
end
end
context "is nonnegative?" do
it "returns true for an integer value greater than or equal to zero" do
expect(0.nonnegative?).to be true
expect(1.nonnegative?).to be true
expect(-1.nonnegative?).to be false
end
end
end
RSpec.describe String do
context "is positive?" do
it "returns true for a positive string" do
expect("y".is_positive?).to be true
expect("yes".is_positive?).to be true
expect("yeah".is_positive?).to be true
expect("ok".is_positive?).to be true
end
it "returns false for a non-positive string" do
expect("maybe".is_positive?).to be false
expect("whatever".is_positive?).to be false
expect("no".is_positive?).to be false
expect("nah".is_positive?).to be false
end
end
context "is negative?" do
it "returns true for a negative string" do
expect("n".is_negative?).to be true
expect("no".is_negative?).to be true
expect("nah".is_negative?).to be true
expect("nope".is_negative?).to be true
end
it "returns false for a non-negative string" do
expect("maybe".is_negative?).to be false
expect("whatever".is_negative?).to be false
expect("sure".is_negative?).to be false
expect("okey dokey".is_negative?).to be false
end
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
# created_at :datetime not null
# updated_at :datetime not null
#
class User < ApplicationRecord
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable, :trackable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :validatable,
:trackable
#判別是否為管理員
def admin?
is_admin
end
# 判別是否收藏
def is_member_of?(job)
favorite_jobs.include?(job)
end
# 加入收藏 #
def add_favorite!(job)
favorite_jobs << job
end
# 移除收藏 #
def remove_favorite!(job)
favorite_jobs.delete(job)
end
has_many :resumes
has_many :favorites
has_many :favorite_jobs, through: :favorites, source: :job
end
|
require 'openssl'
require 'base64'
desc "Encryption tools"
namespace :crypt do
desc "En-crypt a file"
task :en, [:password,:path] do |t, args|
path = File.absolute_path(args[:path])
file = File.basename(path)
password = args[:password]
puts "Encrypting #{path}"
cipher = OpenSSL::Cipher::AES256.new :CBC
cipher.encrypt
iv = cipher.random_iv
safe_iv = Base64.urlsafe_encode64(iv)
cipher.key = Digest::SHA256.digest password
data = File.read(path)
encrypted = cipher.update(data) + cipher.final
final_filename = "#{file}.#{safe_iv}.encrypted"
File.open(final_filename, "wb") do |f|
f.write(encrypted)
end
puts final_filename
end
desc "De-crypt a file"
task :de, [:password,:path] do |t, args|
path = File.absolute_path(args[:path])
unless path =~ /^(.*)\.([A-Za-z0-9\=\-\_]{1,})\.encrypted$/
fail "Specify a filename ending in '.[base64 characters].encrypted'"
end
file = File.basename($1)
puts "Decrypting #{path}"
safe_iv = $2
iv = Base64.urlsafe_decode64(safe_iv)
password = args[:password]
cipher = OpenSSL::Cipher::AES256.new :CBC
cipher.decrypt
cipher.key = Digest::SHA256.digest password
cipher.iv = iv
data = File.read(path)
decrypted = cipher.update(data) + cipher.final
File.open(file, "wb").write(decrypted)
end
end
|
require_relative "Stack"
class SmartStack < Stack
def initialize(num)
@max_size = num
@underlying_array = []
end
def max_size
@max_size
end
def full?
if @underlying_array.length == @max_size
return true
else
return false
end
end
def push(*items)
if items.length + self.size > self.max_size
raise 'stack is full'
end
items.each do |item|
super(item)
end
self.size
end
def pop(n = 1)
removed = []
n.times do
removed << @underlying_array.pop
end
removed
end
end |
class User < ApplicationRecord
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable, :trackable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :validatable
has_many :books
with_options presence: true do
validates :nickname
# validates :first_name
# validates :last_name
end
validates :email, uniqueness: true
PASSWORD_REGEX = /\A(?=.*?[a-z])(?=.*?\d)[a-z\d]+\z/i.freeze
validates_format_of :password, with: PASSWORD_REGEX, message: '6文字以上半角英数字を含めて設定してください'
validates :password, length: { minimum: 6 }
# with_options format: { with: /\A[ぁ-んァ-ヶ一-龥々]+\z/, message: '全角(漢字・ひらがな・カタカナ)で入力してください' } do
# validates :first_name
# validates :last_name
# end
# with_options format: { with: /\A[\p{katakana}ー-&&[^ -~。-゚]]+\z/, message: '全角カタカナを入力して下さい' } do
# validates :first_name_kana
# validates :last_name_kana
# end
end
|
When("I access google website and search for {string}") do |citizens|
@google.visit_url
@google.google_search(citizens)
@google.google_search_button
end
Then("I must find and click on Citizens Advice link") do
@google.result_description
@google.click_result
end |
require_relative '../config/environment.rb'
def reload
load 'config/environment.rb'
end
# Test Code Goes Here
# create three Musical instances
urinetown = Musical.new("Urinetown (Cincy Edition)", "Cincinnati")
lesmis = Musical.new("Les Miserables (Cincy Edition)", "Cincinnati")
spamalot = Musical.new("Spamalot", "Camelot")
puts
puts "Musical.all_introductions outputs:"
puts "(start)"
Musical.all_introductions
puts "(end)"
puts
# create three Theater instances
intiman = Theater.new("Intiman Theater", "Seattle")
aronoff = Theater.new("Aronoff Center", "Cincinnati")
bogarts = Theater.new("Bogarts", "Cincinnati")
puts
puts "Theater.all outputs:"
puts "(start)"
puts Theater.all
puts "(end)"
puts
# test performance_instance.hometown_setting?
performance_cincinnati = Performance.new("Jan 14 1991", urinetown, aronoff)
performance_seattle = Performance.new("Feb 28 2007", urinetown, intiman)
puts
puts "performance_cincinnati.hometown_setting? should return true:"
puts performance_cincinnati.hometown_setting?
puts
puts "performance_seattle.hometown_setting? should return false:"
puts performance_seattle.hometown_setting?
puts
# test urinetown.perform_in_theater("Mar 5 2019", bogarts)
urinetown.perform_in_theater(bogarts, "Mar 5 2019")
puts
puts "check Performance.all to see if Urinetown at Bogarts in 2019 added:"
puts "(start)"
Performance.all_strings
puts "(end)"
puts
# test Musical#performances => does urinetown.performances return an array of Performance instances?
puts
puts "urinetown.performances outputs:"
puts "(start)"
puts urinetown.performances.to_s
puts "(end)"
puts
# test Musical#theaters => does urinetown.theaters return an array of Performance instances?
puts
puts "urinetown.theaters outputs:"
puts "(start)"
puts urinetown.theaters.to_s
puts "(end)"
puts
# test Theater#performances => does aronoff.theaters return an array of Performance instances?
puts
puts "aronoff.performances outputs:"
puts "(start)"
puts aronoff.performances.to_s
puts "(end)"
puts
# test Theater#musicals => does aronoff.musicals return an array of Performance instances?
puts
puts "aronoff.musicals outputs:"
puts "(start)"
puts aronoff.musicals.to_s
puts "(end)"
puts
Pry.start
|
# == Schema Information
#
# Table name: performances
#
# id :integer not null, primary key
# officer :boolean
# referee :boolean
# commander :boolean
# team :integer
# race :string(255)
# player_id :integer
# snapshot_id :integer
#
class Performance < ActiveRecord::Base
belongs_to :player
belongs_to :snapshot
end
|
# frozen_string_literal: true
# wolfram_alpha.rb
# Author: William Woodruff
# ------------------------
# A Cinch plugin that provides Wolfram|Alpha interaction for yossarian-bot.
# ------------------------
# This code is licensed by William Woodruff under the MIT License.
# http://opensource.org/licenses/MIT
require "wolfram"
require_relative "yossarian_plugin"
class WolframAlpha < YossarianPlugin
include Cinch::Plugin
use_blacklist
KEY = ENV["WOLFRAM_ALPHA_APPID_KEY"]
def usage
"!wa <query> - Ask Wolfram|Alpha about <query>. Alias: !wolfram."
end
def match?(cmd)
cmd =~ /^(!)?(wolfram)|(wa)$/
end
match /wa (.+)/, method: :wolfram_alpha, strip_colors: true
match /wolfram (.+)/, method: :wolfram_alpha, strip_colors: true
def wolfram_alpha(m, query)
if KEY
Wolfram.appid = KEY
result = Wolfram.fetch(query).pods[1]
if result && !result.plaintext.empty?
# wolfram alpha formats unicode as \:xxxx for some unknown reason
text = result.plaintext.gsub("\\:", "\\u")
text.unescape_unicode!
text.normalize_whitespace!
m.reply text, true
else
m.reply "Wolfram|Alpha has nothing for #{query}", true
end
else
m.reply "#{self.class.name}: Internal error (missing API key)."
end
end
end
|
class Conversation < ApplicationRecord
has_many :messages, dependent: :restrict_with_exception
end
|
class Giftlist < ActiveRecord::Base
has_many :gifts
belongs_to :user
end
|
class RegisterBrokerController < ApplicationController
def create
user = User.new(params.permit(:title, :first_name, :last_name, :email, :phone, :company_name))
user.role = User::ROLES['COMPANY']
user.address = Address.new
user.password = user.password_confirmation = SecureRandom.hex(5)
if user.save
UserMailer.broker_registered(user.id).deliver_later
StaffMailer.broker_registered_notify_admin(user.id).deliver_later
session[:registered_user_id] = user.id
user.deal.currency = Currency.deal_currency_by_country(session[:country])
user.deal.save!
render json: {next_steps: render_to_string(partial: 'next_steps',
locals: {broker_name: user.name, currency_symbol: user.deal.currency.symbol})}
else
render json: user.errors.full_messages, root: false, status: 422
end
end
def add_card
user = User.find(session[:registered_user_id])
customer = Stripe::Customer.create(
source: params[:stripe_token],
email: user.email,
description: user.name,
metadata: {user_id: user.id}
)
stripe_card = user.stripe_card || user.build_stripe_card
stripe_card.assign_attributes(params.permit(:user_id, :brand, :country_iso, :exp_month,
:exp_year, :last4, :dynamic_last4))
stripe_card.stripe_customer_id = customer.id
stripe_card.save!
user.broker_info.update(payment_method: 'card')
StaffMailer.broker_added_card(user.id).deliver_later
session.delete(:registered_user_id)
render json: {}
rescue Stripe::CardError => e
render json: {error: e.message}, status: :unprocessable_entity
end
end
|
class CreateDiscussionGroupDiscussions < ActiveRecord::Migration
def self.up
create_table :discussion_group_discussions do |t|
t.integer :discussion_group_id
t.integer :discussion_id
t.timestamps
end
end
def self.down
drop_table :discussion_group_discussions
end
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.