text stringlengths 10 2.61M |
|---|
class MergeOnSiteObjectPositionWithSample < ActiveRecord::Migration[6.1]
def change
add_column :samples, :position_description, :text
add_column :samples, :position_x, :decimal
add_column :samples, :position_y, :decimal
add_column :samples, :position_z, :decimal
add_column :samples, :position_crs, :text
execute %(
UPDATE samples
SET
position_description = pos.feature,
position_x = pos."coord_X",
position_y = pos."coord_Y",
position_z = pos."coord_Z",
position_crs = pos.coord_reference_system
FROM on_site_object_positions pos
WHERE samples.on_site_object_position_id = pos.id
)
remove_reference :samples, :on_site_object_position
drop_table :on_site_object_positions
end
end
|
require 'sinatra/base'
require 'sinatra/reloader'
require 'sinatra/json'
module Loadrunner
# The base class for the sinatra server.
# Initialize what we can here, but since there are values that will
# become known only later, the #prepare method is provided.
class ServerBase < Sinatra::Application
set :root, File.expand_path('../../', __dir__)
set :server, :puma
configure :development do
# :nocov: - this is not covered in CI, but is covered in dev
register Sinatra::Reloader if defined? Sinatra::Reloader
# :nocov:
end
# Since we cannot use any config values in the main body of the class,
# since they will be updated later, we need to set anything that relys
# on the config values just before running the server.
# The CommandLine class and the test suite should both call
# `Server.prepare` before calling Server.run!
def self.prepare(opts = {})
set :bind, opts[:bind] || '0.0.0.0'
set :port, opts[:port] || '3000'
end
end
end
|
module F5_Tools
# Handles resolution of names (segments, targets, etc) naively using human-friendly names as keys.
# Motivation was to have a way of having a pool of common resources (like endpoints) without
# having a singleton object manage this.
# This had mixed success, and may/should be refactored at some point.
# Of particular note is whether or not to alarm on duplicate definitions. The correct answer is
# 'yes', but due to the way data is loaded from the YAML, especially when multiple Facilities are
# loaded, this was causing issues.
module Resolution
@@ports = {}
@@segments = {}
@@endpoints = {}
@@nodes = {}
class << self
attr_accessor :warn
end
self.warn = true
include F5_Tools::YAMLUtils
# @param [String] name Segment name
# @param [F5_Object::Segment] seg Segment to be registered
def register_segment(name, seg)
# puts "Warning: Duplicate definition for target #{name}" if @@segments.has_key? name
@@segments[name] = seg
end
def resolve_segment(name, warn = true)
if @@segments.key? name
return @@segments[name]
# Try to infer segemnt from fac. i.e. ORD-WEB
elsif name.include? '-'
fac, seg_name = name.split('-')
yaml = load_or_create_yaml('defs/facilities.yaml')
STDERR.puts "No definition of #{fac.downcase} found.".colorize(:red) unless yaml.key? fac.downcase
facility = F5_Object::Facility.new('cidr_addr' => yaml[fac.downcase]['internal'],
'name' => fac.downcase,
'should_setup' => false)
segments = facility.allocate_segments(false)
throw "No segment #{seg_name} found in #{fac}." unless segments.key? seg_name
return segments[seg_name]
else
throw RuntimeError.new("No definition for segment: #{name}") if warn && Resolution.warn
return nil
end
end
def resolve_endpoint(name, fac_name)
# Return saved address if known
if @@endpoints.key? name
return @@endpoints[name]
# Return 'name' if 'name' is a valid IP
elsif IPAddress.valid? name
return name
# Check Facility endpoint YAML for a definition
else
begin
yaml_path = construct_yaml_path FACILITY_ENDPOINTS_YAML, fac_name
yaml = load_or_create_yaml(yaml_path)
yaml.each do |endpoint|
if name == endpoint['name']
@@endpoints[name] = endpoint['addr']
return endpoint['addr']
end
end
rescue RuntimeError => e
raise e if Resolution.warn
end
# Throw an error if no definition found
throw RuntimeError.new("No definition found for endpoint '#{name}'") if Resolution.warn
end
end
def register_endpoint(name, addr)
@@endpoints[name] = addr
end
# Wipes out known segment map
def clear_segments
@@segments = {}
end
# Tries to resolve a cidr block to a segment object.
# @return Returns a F5_Object::Segment or nil.
def resolve_cidr_to_segment(cidr)
@@segments.each do |name, seg|
return name if cidr == seg.to_s
end
nil
end
# Register a target port symbol
# @param [String] name Port symbol name
# @param [int] port Target port
def register_port(name, port)
@@ports[name.downcase] = port
end
# @param [String] name The port symbol to resolve
# @return Returns port or nil
# @raise Raises if warn is set to true and cannot find the given port
def resolve_port(name, warn = true)
if @@ports.key? name.downcase
return @@ports[name.downcase]
else
STDERR.puts "No definition for target: #{name}".colorize(:red) if warn && Resolution.warn
return nil
end
end
# Wipes out known port symbols
def clear_port_symbols
@@ports = {}
end
# Load iRule data from file
# @param [String] name iRule name
# @return [String] Returns iRule text loaded from iRule file
def get_rule(name)
file_name = "defs/irules/#{name}"
throw "No rule: #{name}" unless File.exist? file_name
File.open(file_name).read
end
# Register a Node. (Used to assert nodes existence)
# @param [String] name Friendly Node name
# @param [F5_Object::Node] node Node to register under name
def register_node(name, node)
@@nodes[name] = node
end
def resolve_node(name, warn = true)
if @@nodes.key? name
return @@nodes[name]
else
STDERR.puts "No definition for node: #{name}" if warn && Resolution.warn
return nil
end
end
end
end
|
require 'spec_helper'
describe Rdf::PropertyExpander, dbscope: :example do
let(:site) { cms_site }
let(:prefix) { "ic" }
# let(:file) { Rails.root.join("db", "seeds", "opendata", "rdf", "ipa-core.ttl") }
let(:file) { Rails.root.join("spec", "fixtures", "rdf", "ipa-core-sample.ttl") }
before do
Rdf::VocabImportJob.new.call(site.host, prefix, file, Rdf::Vocab::OWNER_SYSTEM, 1000)
end
# describe "#expand" do
# let(:rdf_class) { Rdf::Class.search(uri: "http://imi.ipa.go.jp/ns/core/rdf#定期スケジュール型").first }
# subject { described_class.new.expand(rdf_class) }
#
# it do
# expect(subject).not_to be_empty
# expect(subject.length).to be > 5
# expect(subject[0]).to include("ic:種別")
# end
# end
describe "#flattern" do
let(:rdf_class) { Rdf::Class.search(uri: "http://imi.ipa.go.jp/ns/core/rdf#定期スケジュール型").first }
subject { described_class.new.flattern(rdf_class) }
it do
expect(subject).not_to be_empty
expect(subject.length).to be > 5
expect(subject[0]).to include(:ids => include(10),
:names => include("種別"),
:properties => include("ic:種別"),
:classes => include(nil),
:comments => include)
end
end
end
|
#!/usr/bin/env ruby
# https://adventofcode.com/2022/day/3
# --- Day 3: Rucksack Reorganization ---
# One Elf has the important job of loading all of the rucksacks with supplies for the jungle journey. Unfortunately, that Elf didn't quite follow the packing instructions, and so a few items now need to be rearranged.
# Each rucksack has two large compartments. All items of a given type are meant to go into exactly one of the two compartments. The Elf that did the packing failed to follow this rule for exactly one item type per rucksack.
# The Elves have made a list of all of the items currently in each rucksack (your puzzle input), but they need your help finding the errors. Every item type is identified by a single lowercase or uppercase letter (that is, a and A refer to different types of items).
# The list of items for each rucksack is given as characters all on a single line. A given rucksack always has the same number of items in each of its two compartments, so the first half of the characters represent items in the first compartment, while the second half of the characters represent items in the second compartment.
# For example, suppose you have the following list of contents from six rucksacks:
# vJrwpWtwJgWrhcsFMMfFFhFp
# jqHRNqRjqzjGDLGLrsFMfFZSrLrFZsSL
# PmmdzqPrVvPwwTWBwg
# wMqvLMZHhHMvwLHjbvcjnnSBnvTQFn
# ttgJtRGJQctTZtZT
# CrZsJsPPZsGzwwsLwLmpwMDw
# The first rucksack contains the items vJrwpWtwJgWrhcsFMMfFFhFp, which means its first compartment contains the items vJrwpWtwJgWr, while the second compartment contains the items hcsFMMfFFhFp. The only item type that appears in both compartments is lowercase p.
# The second rucksack's compartments contain jqHRNqRjqzjGDLGL and rsFMfFZSrLrFZsSL. The only item type that appears in both compartments is uppercase L.
# The third rucksack's compartments contain PmmdzqPrV and vPwwTWBwg; the only common item type is uppercase P.
# The fourth rucksack's compartments only share item type v.
# The fifth rucksack's compartments only share item type t.
# The sixth rucksack's compartments only share item type s.
# To help prioritize item rearrangement, every item type can be converted to a priority:
# Lowercase item types a through z have priorities 1 through 26.
# Uppercase item types A through Z have priorities 27 through 52.
# In the above example, the priority of the item type that appears in both compartments of each rucksack is 16 (p), 38 (L), 42 (P), 22 (v), 20 (t), and 19 (s); the sum of these is 157.
# Find the item type that appears in both compartments of each rucksack. What is the sum of the priorities of those item types?
require 'set'
def part1(file_name)
file = File.open(file_name)
input_data = file.read
total = 0
input_data.each_line do |line|
line.chomp!
l = line[0..line.length/2-1]
r = line[line.length/2..-1]
sl = Set.new(l.chars)
sr = Set.new(r.chars)
inter = sl & sr
common = inter.to_a
if common.length != 1
raise "Did not find one item common to both"
end
# A=65 -> Z=90
# A=27 -> Z=52
# sub 38 from ascii val
#
# a=97 -> z=122
# a=1 -> z=26
# sub 96 from ascii val
#
ascii = common.first.ord
if ascii >= 65 && ascii <= 90
priority = ascii - 38
elsif ascii >= 97 && ascii <= 122
priority = ascii - 96
else
raise "invalid ascii value #{ascii} for char #{common.first}"
end
total += priority
puts "common=#{common} ascii=#{ascii} priority=#{priority} len=#{line.length} mid=#{line.length/2} #{l.length} #{r.length} l [#{l}] r [#{r}] l=[#{line}]" end
puts "total=#{total}"
end
puts ""
puts "sample"
part1('aoc_03_2022_sample_input.txt')
puts ""
puts "actual"
part1('aoc_03_2022_input.txt')
|
require_relative 'git_hub_adapter'
class CommitterRankFileCreator
def initialize(organization: , project:)
@organization = organization
@project = project
end
def generate_file
@file_name = "#{project_name_formatted}_#{Time.now.strftime("%Y_%m_%d_%H_%M_%S")}.txt"
@committers = GitHubAdapter.new(organization: @organization, project: @project).committers
file = File.open(@file_name, "w") do |f|
@committers.sort{|a,b| b.commit_counter <=> a.commit_counter}.each do |committer|
f.write("#{committer.name};#{committer.email};#{committer.login};#{committer.avatar_url};#{committer.commit_counter};\n")
end
end
@file_name
end
private
def project_name_formatted
@project.downcase.gsub(/[^\w]/,"_")
end
end
|
class Boat
OVERRIDABLE_FIELDS = %w(name new_boat poa location geo_location year_built price length_m
boat_type_id office_id manufacturer_id model_id country_id currency_id
drive_type_id engine_manufacturer_id engine_model_id vat_rate_id
fuel_type_id category_id offer_status length_f state)
module OverridableFields
extend ActiveSupport::Concern
included do
belongs_to :raw_boat, autosave: true, dependent: :destroy
def import_assign(attr_name, value)
if raw_boat
if !field_overridden?(attr_name)
send("#{attr_name}=", value)
end
raw_boat.send("#{attr_name}=", value)
else
send("#{attr_name}=", value)
end
end
def override_imported_value(attr_name, value)
if import_id && !expert_boat? && !raw_boat
build_raw_boat(attributes.slice(*OVERRIDABLE_FIELDS))
end
self[attr_name] = value
end
def imported_field_value(attr_name)
raw_boat ? raw_boat.send(attr_name) : send(attr_name)
end
def field_overridden?(attr_name)
send(attr_name).presence != raw_boat.send(attr_name).presence
end
end
end
end
|
require 'test_helper'
class LocationWebhookTest < ActiveSupport::TestCase
context '#insert' do
before :each do
@json = File.read(Rails.root.join('test', 'modules', 'brewery_db', 'fixtures', 'location.json'))
@attributes = JSON.parse(@json)['data']
@brewery = Factory(:brewery, brewerydb_id: @attributes['breweryId'])
stub_request(:get, /.*api.brewerydb.com.*/).to_return(body: @json)
@webhook = BreweryDB::Webhooks::Location.new({
id: @attributes['id'],
action: 'insert'
})
end
it 'must create a new location' do
@webhook.process
Location.count.must_equal 1
end
it 'must correctly assign attributes to a location' do
@webhook.process
location = Location.find_by(brewerydb_id: @attributes['id'])
assert_attributes_equal(location, @attributes)
location.brewery.must_equal @brewery
end
end
context '#edit' do
before :each do
@json = File.read(Rails.root.join('test', 'modules', 'brewery_db', 'fixtures', 'location.json'))
@attributes = JSON.parse(@json)['data']
stub_request(:get, /.*api.brewerydb.com.*/).to_return(body: @json)
@brewery = Factory(:brewery, brewerydb_id: @attributes['breweryId'])
@webhook = BreweryDB::Webhooks::Location.new({
id: @attributes['id'],
action: 'edit'
})
@location = Factory(:location, brewerydb_id: @attributes['id'], brewery: @brewery)
end
it 'should reassign changed attributes' do
@webhook.process and @location.reload
assert_attributes_equal(@location, @attributes)
end
end
context '#delete' do
it 'should delete the location with the passed brewerydb_id' do
webhook = BreweryDB::Webhooks::Location.new({
id: 'dAvID',
action: 'delete'
})
location = Factory(:location, brewerydb_id: 'dAvID')
webhook.process
lambda { location.reload }.must_raise(ActiveRecord::RecordNotFound)
end
end
private
def assert_attributes_equal(location, attributes)
location.name.must_equal attributes['name']
location.category.must_equal attributes['locationTypeDisplay']
location.wont_be :primary?
location.wont_be :in_planning?
location.must_be :public?
location.wont_be :closed?
location.street.must_equal attributes['streetAddress']
location.street2.must_equal attributes['extendedAddress']
location.city.must_equal attributes['locality']
location.region.must_equal attributes['region']
location.postal_code.must_equal attributes['postalCode']
location.country.must_equal attributes['countryIsoCode']
location.latitude.must_equal attributes['latitude']
location.longitude.must_equal attributes['longitude']
location.phone.must_equal attributes['phone']
location.website.must_equal attributes['website']
location.hours.must_equal attributes['hoursOfOperation']
location.created_at.must_equal Time.zone.parse(attributes['createDate'])
location.updated_at.must_equal Time.zone.parse(attributes['updateDate'])
end
end
|
require 'car'
class Car
class Store
attr_accessor :cars, :csv
def initialize(file, options={})
@csv = load(file)
end
# Returns an array of Car objects.
def cars
groups.map do |id, records|
Car.new(id, records.first[:title], records)
end
end
# Returns a hash of grouped CSV rows, grouped by ID.
def groups
@groups ||= @csv.group_by { |row| row[:id] }
end
# Loads data from CSV file.
def load(file)
rows = CSV.read(file)
headers = rows.shift.map { |col| col.parameterize.underscore.to_sym }
rows.map! { |row| Hash[headers.zip(row)] }
end
end
end
|
class Location < ActiveRecord::Base
has_many :users
has_many :locals, source: :users
has_many :sights
end |
require 'rails_helper'
RSpec.describe CollaboratorsController, type: :controller do
let(:premium_user) { create(:user, role: "premium") }
let(:standard_user) { create(:user) }
let(:private_wiki) { create(:wiki, user_id: premium_user.id, private: true) }
context "premium user" do
before do
sign_in premium_user
end
describe "POST create" do
it "adds a collaborator (standard user) to a private wiki" do
expect { post :create, params: { user_ids: [standard_user.id], wiki_id: private_wiki.id } }.to change(Collaborator,:count).by(1)
end
it "adds the correct user as a collaborator" do
post :create, params: { user_ids: [standard_user.id], wiki_id: private_wiki.id }
expect(private_wiki.users.first).to eq (standard_user)
end
it "removes all collaborators when none are selected for the wiki" do
post :create, params: { user_ids: [standard_user.id], wiki_id: private_wiki.id }
expect(Collaborator.count).to eq 1
post :create, params: { user_ids: [], wiki_id: private_wiki.id }
expect(Collaborator.count).to eq 0
end
it "redirects to the wiki show view" do
post :create, params: { user_ids: [standard_user.id], wiki_id: private_wiki.id }
expect(response).to redirect_to(private_wiki)
end
end
end
end
|
require '../util'
desc 'Creates a VPC'
task :create do
# Creates a VPC
# @see 『Amazon Web Services実践入門』初版 技術評論社 p.117
# @see [aws-cli で使って覚える VPC の作り方と EC2 インスタンスの作り方 - ようへいの日々精進XP]{@link http://inokara.hateblo.jp/entry/2014/03/01/184704}
vpc = aws <<-SH, binding
aws ec2 create-vpc
--cidr-block 10.0.0.0/16
SH
aws <<-SH, binding
aws ec2 create-tags
--resources <%= vpc['Vpc']['VpcId'] %>
--tags 'Key=Name,Value=test-vpc'
SH
# Creates a subnet
# @see 『Amazon Web Services実践入門』初版 技術評論社 pp.119-120
# @see [aws-cli で使って覚える VPC の作り方と EC2 インスタンスの作り方 - ようへいの日々精進XP]{@link http://inokara.hateblo.jp/entry/2014/03/01/184704}
subnet = aws <<-SH, binding
aws ec2 create-subnet
--vpc-id <%= vpc['Vpc']['VpcId'] %>
--cidr-block 10.0.0.0/24
--availability-zone ap-northeast-1c
SH
aws <<-SH, binding
aws ec2 create-tags
--resources <%= subnet['Subnet']['SubnetId'] %>
--tags 'Key=Name,Value=test-vpc'
SH
# Creates an Internet GateWay
# @see 『Amazon Web Services実践入門』初版 技術評論社 p.123
# @see [aws-cli で使って覚える VPC の作り方と EC2 インスタンスの作り方 - ようへいの日々精進XP]{@link http://inokara.hateblo.jp/entry/2014/03/01/184704}
gateway = aws <<-SH, binding
aws ec2 create-internet-gateway
SH
aws <<-SH, binding
aws ec2 create-tags
--resources <%= gateway['InternetGateway']['InternetGatewayId'] %>
--tags 'Key=Name,Value=test-vpc'
SH
# Attaches the gateway to the vpc
# @see 『Amazon Web Services実践入門』初版 技術評論社 p.124
# @see [aws-cli で使って覚える VPC の作り方と EC2 インスタンスの作り方 - ようへいの日々精進XP]{@link http://inokara.hateblo.jp/entry/2014/03/01/184704}
aws <<-SH, binding
aws ec2 attach-internet-gateway
--internet-gateway-id <%= gateway['InternetGateway']['InternetGatewayId'] %>
--vpc-id <%= vpc['Vpc']['VpcId'] %>
SH
# Creates a route to the internet gateway
# @see [aws-cli で使って覚える VPC の作り方と EC2 インスタンスの作り方 - ようへいの日々精進XP]{@link http://inokara.hateblo.jp/entry/2014/03/01/184704}
route_tables = aws <<-SH, binding
aws ec2 describe-route-tables
--filters Name=vpc-id,Values=<%= vpc['Vpc']['VpcId'] %>
--query 'RouteTables[*]'
SH
aws <<-SH, binding
aws ec2 create-route
--route-table-id <%= route_tables[0]['RouteTableId'] %>
--gateway-id <%= gateway['InternetGateway']['InternetGatewayId'] %>
--destination-cidr-block 0.0.0.0/0
SH
# Creates a security group for the vpc
# @see [aws-cli で使って覚える VPC の作り方と EC2 インスタンスの作り方 - ようへいの日々精進XP]{@link http://inokara.hateblo.jp/entry/2014/03/01/184704}
security_group = aws <<-SH, binding
aws ec2 create-security-group
--group-name test-vpc
--description "test vpc"
--vpc-id <%= vpc['Vpc']['VpcId'] %>
SH
aws <<-SH, binding
aws ec2 authorize-security-group-ingress
--group-id <%= security_group['GroupId'] %>
--protocol tcp
--port 22
--cidr 0.0.0.0/0
SH
# Creates an EC2 instance
# @see [aws-cli で使って覚える VPC の作り方と EC2 インスタンスの作り方 - ようへいの日々精進XP]{@link http://inokara.hateblo.jp/entry/2014/03/01/184704}
ec2 = aws <<-SH, binding
aws ec2 run-instances
--image-id ami-383c1956 <%# Amazon Linux %>
--instance-type t2.micro
--key-name default
--security-group-ids <%= security_group['GroupId'] %>
--subnet-id <%= subnet['Subnet']['SubnetId'] %>
--associate-public-ip-address
SH
aws <<-SH, binding
aws ec2 create-tags
--resources <%= ec2['Instances'][0]['InstanceId'] %>
--tags 'Key=Name,Value=test-vpc'
SH
end
|
require 'support/doubled_classes'
module RSpec
module Mocks
RSpec::Matchers.define :fail_expectations_as do |expected|
description { "include a meaningful name in the exception" }
def error_message_for(_)
expect(actual).to have_received(:defined_instance_and_class_method)
rescue MockExpectationError, Expectations::ExpectationNotMetError => e
e.message
else
raise("should have failed but did not")
end
failure_message do |actual|
"expected #{actual.inspect} to fail expectations as:\n" \
" #{expected.inspect}, but failed with:\n" \
" #{@error_message.inspect}"
end
match do |actual|
@error_message = error_message_for(actual)
@error_message.include?(expected)
end
end
RSpec.describe 'Verified double naming' do
shared_examples "a named verifying double" do |type_desc|
context "when a name is given as a string" do
subject { create_double("LoadedClass", "foo") }
it { is_expected.to fail_expectations_as(%Q{#{type_desc}(LoadedClass) "foo"}) }
end
context "when a name is given as a symbol" do
subject { create_double("LoadedClass", :foo) }
it { is_expected.to fail_expectations_as(%Q{#{type_desc}(LoadedClass) :foo}) }
end
context "when no name is given" do
subject { create_double("LoadedClass") }
it { is_expected.to fail_expectations_as(%Q{#{type_desc}(LoadedClass) (anonymous)}) }
end
end
describe "instance_double" do
it_behaves_like "a named verifying double", "InstanceDouble" do
alias :create_double :instance_double
end
end
describe "instance_spy" do
it_behaves_like "a named verifying double", "InstanceDouble" do
alias :create_double :instance_spy
end
end
describe "class_double" do
it_behaves_like "a named verifying double", "ClassDouble" do
alias :create_double :class_double
end
end
describe "class_spy" do
it_behaves_like "a named verifying double", "ClassDouble" do
alias :create_double :class_spy
end
end
describe "object_double" do
it_behaves_like "a named verifying double", "ObjectDouble" do
alias :create_double :object_double
end
end
describe "object_spy" do
it_behaves_like "a named verifying double", "ObjectDouble" do
alias :create_double :object_spy
end
end
end
end
end
|
class RoomsController < ApplicationController
before_action :set_room, only: [:show, :update, :toggle_visibility]
include Filterable
def index
# Filter by characteristics search (returns ActiveRecord relation )
query = filter_composer(filtering_params2)
@filtered_rooms = Room.where(rmrecnbr: query)
# Ransack Search
@q ||= Room.classrooms.ransack(params[:q])
@results ||= policy_scope(@filtered_rooms.merge(@q.result)).includes( :building, :room_panorama_attachment, :room_characteristics, :room_contact, :alerts)
@building_ids ||= @results.pluck(:building_id).uniq.sort
@mappable_locations ||= Building.ann_arbor_campus.with_classrooms.where(id: @building_ids)
@map_sauce = BuildingSerializer.new(@mappable_locations, each_serializer: BuildingSerializer).serializable_hash.to_json
@results = RoomDecorator.decorate_collection(@results)
@pagy, @rooms = pagy(@results, items: 9)
# @rooms_json = serialize_rooms(@results)
@searchable_buildings ||= Building.ann_arbor_campus.with_classrooms.uniq.pluck(:nick_name, :abbreviation).collect{ |building| [building[0].titleize, building[1] ] }.sort
@q.sorts = ["room_number ASC", "instructional_seating_count ASC"] if @q.sorts.empty?
# fresh_when @results
respond_to do |format|
params[:view_preference] ||= "grid_view"
if params[:view_preference] == "list_view"
format.js
format.html
format.json { render json: {entries: render_to_string(partial: "rooms_row", collection: @rooms, as: :room, formats: [:html], cached: true), pagination: view_context.pagy_nav(@pagy) }}
else
format.js
format.html
format.json { render json: {entries: render_to_string(partial: "rooms_card", collection: @rooms, as: :room, formats: [:html], cached: true), pagination: view_context.pagy_nav(@pagy) }}
end
end
end
def show
respond_to do |format|
# format.js
format.html
format.json { render json: @room, serializer: RoomSerializer }
end
end
# def search
# index
# render :index
# end
def update
respond_to do |format|
if @room.update(room_params)
format.html { redirect_to @room, notice: "room was successfully updated." }
format.json { render :show, status: :ok, location: @room }
else
format.html { render :edit }
format.json { render json: @room.errors, status: :unprocessable_entity }
end
end
end
def toggle_visibility
@room.toggle(:visible).save
respond_to do |format|
format.js
end
end
private
def serialize_rooms(rooms)
RoomSerializer.new(rooms, each_serializer: RoomSerializer).serializable_hash.to_json
end
def set_room
fresh_when @room
@room = Room.includes(:building, :room_characteristics, :room_panorama_attachment, :alerts, :room_contact).find(params[:id])
authorize @room
@room_json = serialize_rooms([@room])
@room = @room.decorate
# @room = Room.find_by facility_code_heprod:(params[:id].upcase) || Room.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def room_params
params.require(:room).permit(:rmrecnbr, :floor, :room_number, :facility_code_heprod, :rmtyp_description, :dept_id, :dept_grp, :square_feet, :instructional_seating_count, :building_id, :room_image, :room_panorama, :room_layout, :visible, :page, :view_preference)
end
def filtering_params
params.slice(:bluray, :chalkboard, :doccam, :interactive_screen, :instructor_computer, :lecture_capture, :projector_16mm, :projector_35mm, :projector_digital_cinema, :projector_digial, :projector_slide, :team_board, :team_tables, :team_technology, :vcr, :video_conf, :whiteboard).values
end
def filtering_params2
params.slice(:filter_params)
end
end
|
# frozen_string_literal: true
module Brcobranca
module Boleto
# Banco Unicred
class Unicred < Base
attr_accessor :conta_corrente_dv
validates_length_of :agencia, maximum: 4, message:
'deve ser menor ou igual a 4 dígitos.'
validates_length_of :nosso_numero, maximum: 10, message:
'deve ser menor ou igual a 10 dígitos.'
validates_length_of :conta_corrente, maximum: 9, message:
'deve ser menor ou igual a 9 dígitos.'
# Carteira com 2(dois) caracteres ( SEMPRE 21 )
validates_length_of :carteira, maximum: 2, message:
'deve ser menor ou igual a 2 dígitos.'
validates_length_of :conta_corrente_dv, maximum: 1, message:
'deve ser menor ou igual a 1 dígitos.'
# Nova instancia do Unicred
# @param (see Brcobranca::Boleto::Base#initialize)
def initialize(campos = {})
campos = {
carteira: '21',
local_pagamento: 'PAGÁVEL PREFERENCIALMENTE NAS AGÊNCIAS DA UNICRED',
aceite: 'N'
}.merge!(campos)
super(campos)
end
# Codigo do banco emissor 3 digitos sempre
#
# @return [String] 3 caracteres numericos.
def banco
'136'
end
# Agência do cliente junto ao banco.
# @return [String] 4 caracteres numéricos.
def agencia=(valor)
@agencia = valor.to_s.rjust(4, '0') if valor
end
# Conta corrente
# @return [String] 9 caracteres numéricos.
def conta_corrente=(valor)
@conta_corrente = valor.to_s.rjust(9, '0') if valor
end
# Número seqüencial utilizado para identificar o boleto.
# @return [String] 10 caracteres numéricos.
def nosso_numero=(valor)
@nosso_numero = valor.to_s.rjust(10, '0') if valor
end
# Dígito verificador do nosso número.
#
# @return [String] 1 caracteres numéricos.
def nosso_numero_dv
nosso_numero.to_s.modulo11(mapeamento: {
10 => 0,
11 => 0
})
end
# Nosso número para exibir no boleto.
# @return [String]
# @example
# boleto.nosso_numero_boleto #=> "12345678-4"
def nosso_numero_boleto
"#{nosso_numero}-#{nosso_numero_dv}"
end
# Agência + conta corrente do cliente para exibir no boleto.
# @return [String]
# @example
# boleto.agencia_conta_boleto #=> "08111 / 536788-8"
def agencia_conta_boleto
"#{agencia} / #{conta_corrente}-#{conta_corrente_dv}"
end
# Segunda parte do código de barras.
# Posição | Tamanho | Picture | Conteúdo
# 01-03 | 3 | 9(3) | Identificação da instituição financeira - 136
# 04-04 | 1 | 9 | Código moeda (9 – Real)
# 05-05 | 1 | 9 | Dígito verificador do código de barras (DV)
# 06-19 | 14 | 9(4) | Posições 06 a 09 – fator de vencimento
# | | 9(8)v99 | Posições 10 a 19 – valor nominal do título
# 20-23 | 4 | 4 | Agência BENEFICIÁRIO (Sem o dígito verificador)
# 24-33 | 10 | 10 | Conta do BENEFICIÁRIO (Com o dígito verificador)
# 34–44 | 11 | 11 | Nosso Número (Com o dígito verificador)
# @return [String] 25 caracteres numéricos.
def codigo_barras_segunda_parte
"#{agencia}#{conta_corrente}#{conta_corrente_dv}#{nosso_numero}#{nosso_numero_dv}"
end
end
end
end
|
class SlackIntegrationsController < DashboardController
layout 'dashboard'
def new
@slack_integration = current_organization.build_slack_integration
end
def create
if current_organization.create_slack_integration(integration_params)
redirect_to(integrations_path, notice: notice)
else
redirect_to(new_slack_integration_path, alert: alert)
end
end
private
def integration_params
params.require(:integration_slack).permit(:webhook_url, :channel, :active)
end
def notice
'Integraion created successfully!'
end
def alert
'There was an error creating creating the integraion, please try again'
end
end
|
class AttachmentImage < ApplicationRecord
belongs_to :image
has_attached_file :file
validates_attachment_content_type :file, content_type: ["image/jpg", "image/jpeg", "image/png", "image/gif"]
validates :file, presence: true
end
|
# frozen_string_literal: true
require_relative '../lib/parser'
describe Parser do
subject { Parser.new }
before(:each) do
subject.parse('src/testserver.log')
end
it 'collect each urls visit count' do
subject.show_visits
expect(subject.visits['/help_page/1']).to eq(4)
end
it 'hashes all urls and their visits counts' do
# subject.show_unique_visits
expect(subject.show_visits).to eq(
"/help_page/1: 4 views\n"\
"/home: 2 views\n"\
"/about: 1 view\n"\
"/index: 1 view\n"\
"/about/2: 1 view\n"\
'/contact: 1 view'
)
end
it 'can display formatted results in order of unique visits' do
expect(subject.show_unique_visits).to eq(
"/help_page/1: 3 views\n"\
"/about: 1 view\n"\
"/index: 1 view\n"\
"/about/2: 1 view\n"\
"/home: 1 view\n"\
'/contact: 1 view'
)
end
end
|
Pod::Spec.new do |s|
s.name = "react-native-date-picker-x"
s.version = "1.5.0"
s.license = "MIT"
s.homepage = "https://github.com/henninghall/react-native-date-picker"
s.authors = { 'Henning Hall' => 'henninghall@gmail.com' }
s.summary = "A Cross Platform React Native Picker"
s.source = { :git => "https://github.com/henninghall/react-native-date-picker.git" }
s.source_files = "ios/DatePickerX/*.{h,m}"
s.platform = :ios, "7.0"
s.dependency 'React'
end |
# frozen_string_literal: true
class Brand < ApplicationRecord
include PermissionsConcern
has_many :order_collections
has_many :orders, through: :order_collections
has_one_attached :image
validates :name, :image, :kind_of_pet, :size_type, :min_width, :max_width, :gram_amount, :price, presence: true
validates_numericality_of :max_width, greater_than: :min_width
scope :search_by, ->(param) { where('LOWER(name) LIKE ?', "%#{param.downcase}%") }
scope :by_kind, ->(kind) { where(kind_of_pet: kind) }
scope :by_size, ->(size) { where(size_type: size) }
scope :by_weight, ->(weight) { where('min_width >= ? AND max_width <= ?', weight.to_i - 10, weight) }
end
|
require("minitest/autorun")
require("minitest/rg")
require_relative("../board")
class TestBoard < MiniTest::Test
def setup
@grid_positions = [[4,6], 0, 0, 0, 0, 0, 0]
@board = Board.new(grid_positions)
end
def test_check_length
assert_equal(8, @board.length_of_grid)
end
end
|
# input: string
# output: boolean depending on whether input string is balanced or not
# rules:
# the method returns true if all parentheses in the string are properly balanced
# balanced = parentheses occur in matching pairs '(' and ')'
# opposite facing parentheses ')' and '(' are not balanced
# if the input string does not have any parentheses then the method returns true, assumes it is balanced
# the input string can have multiple parentheses, as long as they are all balanced then method will return true
# balanced pairs = each '(' ')' have to be in pairs
# balanced pairs must start with a '('
# balanced pairs if the number of each parentheses is the same
# data structure: array
# algorithm:
# set a variable and assign to an empty array
# iterate through input string and push each parentheses into array variable
# if the first element parentheses is the closing parentheses then return false
# count the number of each parentheses and if they equal each other then return true, if not then return false
# if there are no parentheses, return true
def parentheses_array_check(array)
opening_count = 0
closing_count = 0
array.each do |char|
if char == ')'
opening_count += 1
elsif char == '('
closing_count += 1
end
end
if opening_count == closing_count
return true
else
return false
end
end
def balanced?(string)
parentheses = []
string_chars = string.chars
string_chars.each do |char|
if char == '(' || char == ')'
parentheses << char
end
end
if parentheses[0] == ')'
return false
elsif parentheses.empty?
return true
elsif parentheses[-1] == '('
return false
end
result = parentheses_array_check(parentheses)
end
# or
def balanced?(string)
parens = 0
string.each_char do |char|
parens += 1 if char == '('
parens -= 1 if char == ')'
break if parens < 0
end
parens.zero?
end |
class MapaImpuestoEstado
def initialize()
@UT = 0.0685
@NV = 0.08
@TX = 0.0625
@AL = 0.04
@CA = 0.0825
end
def getUT()
"#{@UT}"
end
def getNV()
"#{@NV}"
end
def getTX()
"#{@TX}"
end
def getAL()
"#{@AL}"
end
def getCA()
"#{@CA}"
end
end
class Descuento
def initialize()
@rango1 = 0
@rango2 = 3
@rango3 = 5
@rango4 = 7
@rango5 = 10
@rango6 = 15
end
def getDescuento(montoSubTotal)
case montoSubTotal
when 0..1000
@rango1
when 1001..5000
@rango2
when 5001..7000
@rango3
when 7001..10000
@rango4
when 10001..50000
@rango5
else
@rango6
end
end
end
class Factura
def initialize(cantidad , precioUnitario, estado)
@mapImpuestoEstado = MapaImpuestoEstado.new()
@cantidad = cantidad.to_i
@precioUnitario = precioUnitario.to_f
@estado = estado
end
def calculoSubTotal()
@subTotal = @cantidad * @precioUnitario.to_f
"#{@subTotal}"
end
def obtenerImpuestoEstado()
@impuestoEstado = {"UT"=> @mapImpuestoEstado.getUT(), "NV"=> @mapImpuestoEstado.getNV(), "TX"=> @mapImpuestoEstado.getTX(), "AL"=> @mapImpuestoEstado.getAL(), "CA"=> @mapImpuestoEstado.getCA()}[@estado]
"#{@impuestoEstado}"
end
def calculoImpuesto()
@impuesto = @subTotal * @impuestoEstado.to_f
"#{@impuesto}"
end
def obtenerDescuentoMonto()
objDescuento = Descuento.new()
@descuentoMonto= objDescuento.getDescuento(@subTotal + @impuesto)
end
def calculoDescuento()
@descuento = (@subTotal + @impuesto) * ( @descuentoMonto*0.01)
"#{@descuento}"
end
def calculoTotal()
@total = @subTotal+@impuesto - @descuento
"#{@total}"
end
def getEstado()
"#{@estado}"
end
def getImpuestoEstadoImpresion()
obtenerImpuestoEstado()
impuestoEstadoImpresion = @impuestoEstado.to_f * 100
"#{impuestoEstadoImpresion}"
end
def getDescuentoMonto()
"#{@descuentoMonto}"
end
end
factura = Factura.new(ARGV[0],ARGV[1], ARGV[2])
puts "# #{ARGV[0]} * $#{ARGV[1]} = $" + factura.calculoSubTotal()
puts "#{factura.getEstado}(%#{factura.getImpuestoEstadoImpresion}) = $"+factura.calculoImpuesto()
factura.obtenerDescuentoMonto()
puts "DTO(%#{factura.getDescuentoMonto}) = $"+factura.calculoDescuento()
puts "Total = $"+factura.calculoTotal() |
class RemoveTwtmFromParticipations < ActiveRecord::Migration
def change
remove_column :participations, :twtm, :integer
end
end
|
name 'firefox_configuration'
maintainer 'Alex Markessinis'
maintainer_email 'markea125@gmail.com'
license 'MIT'
description 'Configures FireFox'
long_description IO.read(File.join(File.dirname(__FILE__), 'README.md'))
issues_url 'https://github.com/MelonSmasher/chef_firefox_configuration/issues' if respond_to?(:issues_url)
source_url 'https://github.com/MelonSmasher/chef_firefox_configuration' if respond_to?(:source_url)
version '0.2.1'
supports 'windows'
supports 'mac_os_x'
suggest 'firefox' |
class ContactsController < ApplicationController
def index
render_json current_user.paginated_contacts(pagination_params), each_serializer: UserWithEmailsAndPhonesSerializer
end
def add
# TODO emails?
phone_numbers = split_param(:phone_numbers).map{ |n| Phone.normalize(n) }
contact_inviter = ContactInviter.new(current_user)
users = contact_inviter.add_by_phone_numbers_only(phone_numbers, {skip_sending: !send_sms_invites?, source: params[:source]})
users = User.includes(:account, :avatar_image, :avatar_video, :phones, :emails).where(id: users.map(&:id))
render_json users, each_serializer: UserWithEmailsAndPhonesSerializer
end
def remove
user_ids = split_param(:user_ids)
ContactInviter.new(current_user).remove_users(user_ids)
render_json User.where(id: user_ids)
end
def autoconnect
hashed_emails = split_param(:hashed_emails)
hashed_phone_numbers = split_param(:hashed_phone_numbers)
added_users = ContactInviter.new(current_user).autoconnect(hashed_emails, hashed_phone_numbers)
user_ids = added_users.map(&:id)
current_user.matching_phone_contact_user_ids << user_ids if user_ids.present?
mixpanel.shared_contacts
render_json added_users, each_serializer: UserWithEmailsAndPhonesSerializer
end
end
|
require 'test_helper'
class LeaveRecordsControllerTest < ActionDispatch::IntegrationTest
setup do
@leave_record = leave_records(:one)
end
test "should get index" do
get leave_records_url
assert_response :success
end
test "should get new" do
get new_leave_record_url
assert_response :success
end
test "should create leave_record" do
assert_difference('LeaveRecord.count') do
post leave_records_url, params: { leave_record: { al: @leave_record.al, cl: @leave_record.cl, created_at: @leave_record.created_at, date_of_rejoining: @leave_record.date_of_rejoining, from: @leave_record.from, id: @leave_record.id, not_returned_on_date: @leave_record.not_returned_on_date, professional_detail_id: @leave_record.professional_detail_id, to: @leave_record.to, total_no_of_days: @leave_record.total_no_of_days, type_of_leave: @leave_record.type_of_leave, updated_at: @leave_record.updated_at } }
end
assert_redirected_to leave_record_url(LeaveRecord.last)
end
test "should show leave_record" do
get leave_record_url(@leave_record)
assert_response :success
end
test "should get edit" do
get edit_leave_record_url(@leave_record)
assert_response :success
end
test "should update leave_record" do
patch leave_record_url(@leave_record), params: { leave_record: { al: @leave_record.al, cl: @leave_record.cl, created_at: @leave_record.created_at, date_of_rejoining: @leave_record.date_of_rejoining, from: @leave_record.from, id: @leave_record.id, not_returned_on_date: @leave_record.not_returned_on_date, professional_detail_id: @leave_record.professional_detail_id, to: @leave_record.to, total_no_of_days: @leave_record.total_no_of_days, type_of_leave: @leave_record.type_of_leave, updated_at: @leave_record.updated_at } }
assert_redirected_to leave_record_url(@leave_record)
end
test "should destroy leave_record" do
assert_difference('LeaveRecord.count', -1) do
delete leave_record_url(@leave_record)
end
assert_redirected_to leave_records_url
end
end
|
class Users::TradeRequests::OffersController < Users::BaseController
before_action :get_offer
def approve
service = OfferService.new(current_user, @offer)
service.approve
if service.save!
redirect_to request.referer,
notice: 'Offer approved.'
end
end
def decline
service = OfferService.new(current_user, @offer)
service.decline
if service.save!
redirect_to request.referer,
notice: 'Offer declined.'
end
end
private
def get_offer
@offer = current_user.trade_request_offers.find(params[:offer_id])
if @offer.nil? or not @offer.pending?
redirect_to trade_requests_path
end
end
end
|
#encoding: utf-8
require 'spec_helper'
describe PartidaContable do
before do
@attr = {:importe => 1000, :importe_currency => "USD"}
end
describe "validación de propiedades" do
before do
@pc = Factory(:partida_contable)
end
it "debe responder a las propiedades" do
@pc.should respond_to(:fecha_de_vencimiento)
@pc.should respond_to(:empresa)
@pc.should respond_to(:banco)
@pc.should respond_to(:solicitante)
@pc.should respond_to(:canal_de_solicitud)
@pc.should respond_to(:rubro)
@pc.should respond_to(:importe)
@pc.should respond_to(:importe_cents)
@pc.should respond_to(:importe_currency)
@pc.should respond_to(:valor_dolar)
@pc.should respond_to(:valor_dolar_cents)
@pc.should respond_to(:valor_dolar_currency)
@pc.should respond_to(:tipo_de_movimiento)
@pc.should respond_to(:cliente_proveedor)
@pc.should respond_to(:detalle)
@pc.should respond_to(:producto_trabajo)
@pc.should respond_to(:estado)
@pc.should respond_to(:motivo_de_baja_presupuestaria)
@pc.should respond_to(:deleted_at)
end
it "importe es del tipo money" do
# @pc = Factory(:partida_contable, :importe_cents => 100000)
@pc.importe == Money.new(@attr[:importe], @attr[:importe_currency])
end
it "valor_dolar es del tipo money" do
# @pc = Factory(:partida_contable, :importe_cents => 100000)
@pc.valor_dolar == Money.new(@attr[:importe], @attr[:importe_currency])
end
describe "fecha_de_vencimiento" do
it "debe ser requerido" do
@pc.fecha_de_vencimiento = nil
@pc.should_not be_valid
end
end
describe "empresa" do
it "debe ser requerido" do
@pc.empresa = nil
@pc.should_not be_valid
end
end
describe "solicitante" do
it "debe ser requerido" do
@pc.solicitante = nil
@pc.should_not be_valid
end
end
describe "canal_de_solicitud" do
it "debe ser requerido" do
@pc.canal_de_solicitud = nil
@pc.should_not be_valid
end
end
describe "rubro" do
it "debe ser requerido" do
@pc.rubro = nil
@pc.should_not be_valid
end
end
describe "tipo_de_movimiento" do
it "debe ser requerido" do
@pc.tipo_de_movimiento = nil
@pc.should_not be_valid
end
end
describe "cliente_proveedor" do
it "debe ser requerido" do
@pc.cliente_proveedor = nil
@pc.should_not be_valid
end
end
describe "producto_trabajo" do
it "debe ser requerido" do
@pc.producto_trabajo = nil
@pc.should_not be_valid
end
end
describe "estado" do
it "debe ser requerido" do
@pc.estado = nil
@pc.should_not be_valid
end
it "debe estar como activa" do
@pc.estado.should == PartidaContable::ESTADOS[:activa]
end
it "no puede ser nulo" do
@pc.estado = nil
@pc.save
@pc.reload
@pc.estado.should == PartidaContable::ESTADOS[:activa]
end
it "no debe aceptar valores" do
@pc.estado = 23
@pc.should_not be_valid
end
# it "debe cambiar el estado a anulada" do
# @cancelacion.anular
# @cancelacion.estado.should == PartidaContable::ESTADOS[:anulada]
# end
end
describe "importe" do
it "importe es del tipo money" do
@pc.importe = nil
@pc.should_not be_changed
end
it "should require nonblank content" do
@pc.importe = Money.new("", @attr[:importe_currency])
@pc.should_not be_valid
end
it "no puede ser nulo" do
@pc.importe = Money.new(nil, @attr[:importe_currency])
@pc.should_not be_valid
end
it "should require nonblank content" do
@pc.importe = Money.new("a", @attr[:importe_currency])
@pc.should_not be_valid
end
it "no puede ser cero" do
@pc.importe = Money.new(0.00, @attr[:importe_currency])
@pc.should_not be_valid
end
it "no puede ser inferior a cero" do
@pc.importe = Money.new(-0.01, @attr[:importe_currency])
@pc.should_not be_valid
end
it "should require nonblank content" do
lambda do
@pc.importe = Money.new(@attr[:importe_cents], "")
end.should raise_error(Money::Currency::UnknownCurrency)
end
end
describe "valor_dolar" do
it "valor_dolar es del tipo money" do
@pc.valor_dolar = nil
@pc.should_not be_changed
end
it "should require nonblank content" do
@pc.valor_dolar = Money.new("", @attr[:valor_dolar_currency])
@pc.should_not be_valid
end
it "no puede ser nulo" do
@pc.valor_dolar = Money.new(nil, @attr[:valor_dolar_currency])
@pc.should_not be_valid
end
it "should require nonblank content" do
@pc.valor_dolar = Money.new("a", @attr[:valor_dolar_currency])
@pc.should_not be_valid
end
it "no puede ser cero" do
@pc.valor_dolar = Money.new(0.00, @attr[:valor_dolar_currency])
@pc.should_not be_valid
end
it "no puede ser inferior a cero" do
@pc.valor_dolar = Money.new(-0.01, @attr[:valor_dolar_currency])
@pc.should_not be_valid
end
it "should require nonblank content" do
lambda do
@pc.valor_dolar = Money.new(@attr[:valor_dolar_cents], "")
end.should raise_error(Money::Currency::UnknownCurrency)
end
end
describe "Detalle" do
it "debe ser requerido" do
@pc.detalle = nil
@pc.should_not be_valid
end
it "debe contener algún dato" do
@pc.detalle = ""
@pc.should_not be_valid
end
end
end
describe "asociación con cancelación" do
before do
@pc = Factory(:partida_contable, :importe_cents => 100000)
end
it "debe responder a las cancelaciones" do
@pc.should respond_to(:cancelaciones)
end
it "debe responder a resta cancelar" do
@pc.should respond_to(:resta_cancelar)
end
it "debe responder a importe total cancelado" do
@pc.should respond_to(:importe_total_cancelado)
end
it "debe responder a dar por cumplida" do
@pc.should respond_to(:dar_por_cumplida)
end
it "debe cambiar el estado de la partida contable a parcial" do
# @medio_de_pago = Factory(:medio_de_pago)
@pc.cancelaciones.build(:medio_de_pago => Factory(:medio_de_pago), :fecha_de_ingreso => DateTime.now, :importe => Money.new(1356, "USD"), :valor_dolar => Money.new(607, "ARS"))
@pc.save
@pc.reload
@pc.estado.should == PartidaContable::ESTADOS[:parcial]
end
it "no debe cambiar el estado de la partida contable a parcial" do
@medio_de_pago = Factory(:medio_de_pago)
PartidaContable.any_instance.stub(:save).and_return(false)
@pc.cancelaciones.build(:medio_de_pago => @medio_de_pago, :fecha_de_ingreso => DateTime.now, :importe => Money.new(1356, "USD"), :valor_dolar => Money.new(607, "ARS"))
@pc.save
@pc.reload
@pc.estado.should == PartidaContable::ESTADOS[:activa]
end
describe "cancelaciones activas" do
before do
@attr = { :medio_de_pago => Factory(:medio_de_pago), :fecha_de_ingreso => DateTime.now, :importe => Money.new(91050, "ARS"), :valor_dolar => Money.new(607, "ARS")}
@cancelacion1 = @pc.cancelaciones.create!(@attr)
@cancelacion2 = @pc.cancelaciones.create!(@attr.merge(:importe => Money.new(121400, "ARS")))
@cancelacion3 = @pc.cancelaciones.create!(@attr.merge(:importe => Money.new(242800, "ARS")))
@cancelacion2.anular
@cancelacion2.save
end
it "debe mostrar la suma de las cancelaciones activas" do
@pc.importe_total_cancelado.should == Money.new(333850,"ARS")
end
it "obtener las cancelaciones activas de la partida contable correspondiente" do
@pc2 = Factory(:partida_contable)
@medio_de_pago = Factory(:medio_de_pago)
@attr2 = { :medio_de_pago => @medio_de_pago, :fecha_de_ingreso => DateTime.now, :importe => Money.new(8231, "ARS"), :valor_dolar => Money.new(607, "ARS")}
@cancelacion4pc2 = @pc2.cancelaciones.create!(@attr2)
@pc.cancelaciones_activas.should == [@cancelacion1, @cancelacion3]
@pc2.cancelaciones_activas.should == [@cancelacion4pc2]
end
end
# it "debe responder a adicionar_cancelacion" do
# @pc.should respond_to(:adicionar_cancelacion)
# end
# it "debe responder a eliminar_cancelacion" do
# @pc.should respond_to(:eliminar_cancelacion)
# end
# it "debe adicionar una cancelacion a la partida contable" do
# @medio_de_pago = Factory(:medio_de_pago)
# @cancelacion = Cancelacion.build(:medio_de_pago => @medio_de_pago, :fecha_de_ingreso => DateTime.now, :importe => Money.new(150, "USD")})
# @pc.adicionar_cancelacion
# @pc.cancelaciones.first
# end
end
describe "importe total cancelado" do
before do
# @attr = { :medio_de_pago => Factory(:medio_de_pago), :fecha_de_ingreso => DateTime.now, :importe => Money.new(150, "USD"), :valor_dolar => Money.new(607, "ARS")}
# Money.add_rate("USD", "ARS", "6.07")
end
it "si no tiene ninguna cancelación el resultado debe ser cero" do
@pc = Factory(:partida_contable)
@pc.cancelaciones.count.should == 0
@pc.importe_total_cancelado.should == Money.new(0, "ARS")
end
it "debe sumar las cancelaciones de la misma moneda" do
@pc = Factory(:partida_contable)
@attr = { :medio_de_pago => Factory(:medio_de_pago), :fecha_de_ingreso => DateTime.now, :importe => Money.new(31254, "ARS"), :valor_dolar => Money.new(607, "ARS")}
@pc.cancelaciones.create!(@attr)
@pc.cancelaciones.create!(@attr.merge(:importe => Money.new(2398, "ARS")))
@pc.importe_total_cancelado.should == Money.new(33652, "ARS")
end
describe "suma de cancelaciones de distintas monedas" do
it "partida contable en pesos con una cancelación en dólares" do
# Money.add_rate("USD", "ARS", "6.07")
@pc = Factory(:partida_contable)
@attr = { :medio_de_pago => Factory(:medio_de_pago), :fecha_de_ingreso => DateTime.now, :importe => Money.new(91050, "ARS"), :valor_dolar => Money.new(607, "ARS")}
@pc.cancelaciones.create!(@attr)
@pc.cancelaciones.create!(@attr.merge(:importe => Money.new(20000, "USD")))
@pc.importe_total_cancelado.should == Money.new(212450, "ARS")
end
it "partida contable en dólares con una cancelación en pesos" do
# Money.add_rate("ARS", "USD", "0.164744646")
@pc = Factory(:partida_contable, :importe_cents => 10000, :importe_currency => "USD")
@attr = { :medio_de_pago => Factory(:medio_de_pago), :fecha_de_ingreso => DateTime.now, :importe => Money.new(23000, "ARS"), :valor_dolar => Money.new(607, "ARS")}
@pc.cancelaciones.create!(@attr)
@pc.cancelaciones.create!(@attr.merge(:importe => Money.new(2396, "USD")))
@pc.importe_total_cancelado.should == Money.new(6185, "USD")
end
end
end
describe "resta cancelar" do
it "si no tiene ninguna cancelación debe mostrar el monto de la partida contable" do
@pc = Factory(:partida_contable)
@pc.resta_cancelar.should == @pc.importe
end
it "con una cancelación en la misma" do
@pc = Factory(:partida_contable, :importe_cents => 100000)
@attr = { :medio_de_pago => Factory(:medio_de_pago), :fecha_de_ingreso => DateTime.now, :importe => Money.new(23415, "ARS"), :valor_dolar => Money.new(607, "ARS")}
@pc.cancelaciones.create!(@attr)
@pc.resta_cancelar.should == Money.new(76585,"ARS")
end
describe "suma de cancelaciones de distintas monedas" do
it "partida contable en pesos con una cancelación en dólares" do
@pc = Factory(:partida_contable, :importe_cents => 100000)
@attr = { :medio_de_pago => Factory(:medio_de_pago), :fecha_de_ingreso => DateTime.now, :importe => Money.new(150, "USD"), :valor_dolar => Money.new(607, "ARS")}
@pc.cancelaciones.create!(@attr)
@pc.cancelaciones.create!(@attr.merge(:importe => Money.new(23116, "ARS")))
@pc.resta_cancelar.should == Money.new(75974, "ARS")
end
it "partida contable en pesos con una cancelación en dólares con distintas cotizaciones" do
@pc = Factory(:partida_contable, :importe_cents => 100000)
@attr = { :medio_de_pago => Factory(:medio_de_pago), :fecha_de_ingreso => DateTime.now, :importe => Money.new(150, "USD"), :valor_dolar => Money.new(631, "ARS")}
@pc.cancelaciones.create!(@attr)
@pc.cancelaciones.create!(@attr.merge(:importe => Money.new(23116, "ARS")))
@pc.resta_cancelar.should == Money.new(75938, "ARS")
end
it "partida contable en dólares con una cancelación en pesos" do
@pc = Factory(:partida_contable, :importe_cents => 10000, :importe_currency => "USD")
@attr = { :medio_de_pago => Factory(:medio_de_pago), :fecha_de_ingreso => DateTime.now, :importe => Money.new(23000, "ARS"), :valor_dolar => Money.new(607, "ARS")}
@pc.cancelaciones.create!(@attr)
@pc.cancelaciones.create!(@attr.merge(:importe => Money.new(2396, "USD")))
@pc.resta_cancelar.should == Money.new(3815, "USD")
end
it "partida contable en dólares con una cancelación en pesos con distintas cotizaciones" do
@pc = Factory(:partida_contable, :importe_cents => 10000, :importe_currency => "USD")
@attr = { :medio_de_pago => Factory(:medio_de_pago), :fecha_de_ingreso => DateTime.now, :importe => Money.new(23000, "ARS"), :valor_dolar => Money.new(631, "ARS")}
@pc.cancelaciones.create!(@attr)
@pc.cancelaciones.create!(@attr.merge(:importe => Money.new(2396, "USD")))
@pc.resta_cancelar.should == Money.new(3959, "USD")
end
end
end
describe "dar por cumplida" do
it "debe cambiar el estado a cumplida" do
@pc = Factory(:partida_contable, :importe_cents => 100000)
@pc.dar_por_cumplida
@pc.estado.should == PartidaContable::ESTADOS[:cumplida]
end
end
describe "verificación de asociación con partidas_contable" do
before do
@empresa = Factory(:empresa)
@banco = Factory(:banco)
@solicitante = Factory(:solicitante)
@canal_de_solicitud = Factory(:canal_de_solicitud)
@rubro = Factory(:rubro)
@medio_de_pago = Factory(:medio_de_pago)
@cliente_proveedor = Factory(:cliente_proveedor)
@producto_trabajo = Factory(:producto_trabajo)
@attr2 = { :fecha_de_vencimiento => DateTime.now, :importe => 1356 , :importe_currency => "EUR", :valor_dolar => Money.new(4, "ARS"),
:solicitante_id => @solicitante, :canal_de_solicitud_id => @canal_de_solicitud, :rubro_id => @rubro, :cliente_proveedor_id => @cliente_proveedor,
:producto_trabajo_id => @producto_trabajo, :tipo_de_movimiento => 1, :detalle => "texto" }
@pc = @empresa.partidas_contable.create!(@attr2)
end
it "debe tener los pcs asociados" do
@pc.empresa_id.should == @empresa.id
@pc.empresa.should == @empresa
end
it "obtener las pcs pendientes de una empresa" do
end
end
end
|
# A Site groups bookmarks togehter by their base URL.
# Therefore the AR class will always "sanitize" non-base
# URLs used in interacting with this class by trimming the
# URL to its base URL. This is achieved by using a Serializer.
class Site < ApplicationRecord
class UrlSerializer
def dump value
BaseUrl.new(value).trim
end
def load value
value
end
end
private_constant :UrlSerializer
has_many :bookmarks, dependent: :destroy
serialize :url, UrlSerializer.new
validates :url, presence: true, uniqueness: true, http_url: true
def has_bookmarks?
bookmarks_count > 0
end
def single_bookmark?
bookmarks_count == 1
end
# Deletes the Site if there are no more bookmarks associated
def destroy_if_orphaned
destroy unless has_bookmarks?
end
end
|
namespace :cron do
namespace :mygofer do
# all tasks related to fetching and parsing the soc_com feed
namespace :soc_com do
task :init_soc_com => :environment do
MYGOFER1=Source['mygofer'].dup
MYGOFER2=Source['mygofer'].dup
def MYGOFER1.abbrev; 'MG'; end
def MYGOFER1.pid_length; 16; end
def MYGOFER2.abbrev; 'MG2'; end
def MYGOFER2.pid_length; 16; end
end
task :all => :init_soc_com do
# set up a quick abbrev method so we don't have to pass an extra variable or constantly case..end
# for each source...
[MYGOFER1, MYGOFER2].each do |source|
Rake::Task['cron:mygofer:soc_com:fetch'].invoke source
Rake::Task['cron:mygofer:soc_com:fetch'].reenable
Rake::Task['cron:mygofer:soc_com:remove_old_prices'].invoke source
Rake::Task['cron:mygofer:soc_com:remove_old_prices'].reenable
Rake::Task['cron:mygofer:soc_com:load_feed'].invoke source
Rake::Task['cron:mygofer:soc_com:load_feed'].reenable
end
end
task :fetch, :source, :needs => :init_soc_com do |t, args|
unless system("./script/fetch_soc_com_feed.sh #{SOC_COM_DIR} #{args[:source].abbrev}")
raise "fetch_soc_com_feed.sh failed #{$?}"
end
end
task :remove_old_prices, :source, :needs => :init_soc_com do |t, args|
RAILS_DEFAULT_LOGGER.auto_flushing = true # to insure logging
file = ENV['FILE']
file ||= "#{SOC_COM_DIR}/#{args[:source].abbrev}_removed.txt"
# The Mysears SocComRemoveParser is generic enough to be reused here
Mysears::SocComRemoveParser.new(file, args[:source], args[:source].pid_length).parse
end
task :first_mygofer => :init_soc_com do
Rake::Task['cron:mygofer:soc_com:load_feed'].invoke MYGOFER1
Rake::Task['cron:mygofer:soc_com:load_feed'].reenable
Rake::Task['cron:mygofer:soc_com:load_feed'].invoke MYGOFER2
end
desc 'Loads the Social Commerce product feed provided by SHC'
task :load_feed, :source, :needs => :init_soc_com do |t, args|
RAILS_DEFAULT_LOGGER.auto_flushing = true # to insure logging
file = ENV['FILE']
file ||= "#{SOC_COM_DIR}/#{args[:source].abbrev}_new_or_changed.txt"
Mygofer::SocComParser.new(file, args[:source], args[:source].pid_length).parse
end
end # of namespace soc_com
end # of namespace mygofer
end # of namespace cron
|
class CompaniesController < ApplicationController
def create
@company = current_user.companies.build(params[:company])
if @company.save
flash[:success] = "Company created!"
redirect_to root_path
else
flash[:error] = "Something went wrong, try again please..."
render 'pages/home'
end
end
def show
begin
@company = Company.find(params[:id])
rescue
flash[:error] = "Company not found."
redirect_to root_path
end
end
def edit
end
def destroy
end
end
|
module Myimdb
module Scraper
class Imdb < Scraper::Base
def initialize(url)
@url = url
end
def directors
document.css('#overview-top .txt-block h4:contains("Director") ~ a:not(:contains(" more "))').collect{ |a| a.text }
end
def directors_with_url
document.css('#overview-top .txt-block h4:contains("Director") ~ a:not(:contains(" more "))').collect{ |a| {:name=> a.text, :url=> "http://www.imdb.com#{a['href']}" } }
end
def writers
document.css('#overview-top .txt-block h4:contains("Writer") ~ a:not(:contains(" more "))').collect{ |a| a.text }
end
def writers_with_url
document.css('#overview-top .txt-block h4:contains("Writer") ~ a:not(:contains(" more "))').collect{ |a| {:name=> a.text, :url=> "http://www.imdb.com#{a['href']}" } }
end
def rating
document.css(".star-box-details span[itemprop='ratingValue']").inner_text.strip.to_f
end
def votes
document.css(".star-box a[href='ratings']").inner_text.strip.split(' ').first.sub(',', '').to_i
end
def genres
document.css('.see-more.inline.canwrap h4:contains("Genres:") ~ a:not(:contains(" more "))').collect{ |a| a.text }
end
def tagline
strip_useless_chars(document.css('.txt-block h4:contains("Taglines:")').first.parent.inner_text).gsub(/Taglines |See more/, '') rescue nil
end
def plot
strip_useless_chars(document.css('.article h2:contains("Storyline") ~ p').inner_text).gsub(/Written by.*/, '')
end
def year
release_date.year
end
def release_date
Date.parse(document.css("a[title='See all release dates']").inner_text)
end
def image
document.css('#img_primary img').first['src']
end
private
def document
@document ||= Nokogiri::HTML(open(@url))
end
handle_exceptions_for :directors, :directors_with_url, :writers, :writers_with_url, :rating, :votes, :genres, :tagline, :plot, :year, :image
end
end
end |
#encoding: utf-8
module Model
class Cultist
def initialize(name,gained)
@name = name
@gainedLevels = gained
end
def getBasicValue
@gainedLevels
end
def getSpecialValue
return (@gainedLevels*CultistPlayer.getCultistPlayers)
end
def to_s
return @name + "\n" + "niveles ganados: " + @gainedLevels.to_s
end
end
end |
# Be sure to restart your server when you modify this file.
session_store_key_name = ENV['SESSION_STORE_KEY_NAME']
valid_session_store_key_name = session_store_key_name.is_a?(String) && session_store_key_name.present?
raise "Please define a cookie_store key at `config/initializers/session_store.rb` (or in your .env file under SESSION_STORE_KEY_NAME)" unless valid_session_store_key_name
# Use a different cookie for each environment
session_store_key = "_#{session_store_key_name}-#{Rails.env}"
Rails.application.config.session_store :cookie_store, key: session_store_key
|
# frozen_string_literal: true
class ReviewsController < ApplicationController
permits :title, :body, :rating_animation_state, :rating_music_state, :rating_story_state,
:rating_character_state, :rating_overall_state
impressionist actions: %i(show)
before_action :authenticate_user!, only: %i(new create edit update destroy)
before_action :load_user, only: %i(index show)
before_action :load_work, only: %i(new create edit update destroy)
before_action :load_review, only: %i(show)
def index(page: nil)
@reviews = @user.
reviews.
includes(work: :work_image).
published
@reviews = localable_resources(@reviews)
@reviews = @reviews.order(created_at: :desc).page(page)
return unless user_signed_in?
@works = Work.where(id: @reviews.pluck(:work_id))
store_page_params(works: @works)
end
def show
@work = @review.work
@is_spoiler = user_signed_in? && current_user.hide_review?(@review)
@reviews = @user.
reviews.
published.
where.not(id: @review.id).
includes(work: :work_image).
order(id: :desc)
store_page_params(work: @work)
end
def new
@review = @work.reviews.new
store_page_params(work: @work)
end
def create(review)
@review = @work.reviews.new(review)
@review.user = current_user
current_user.setting.attributes = setting_params
ga_client.page_category = params[:page_category]
service = NewReviewService.new(current_user, @review, current_user.setting)
service.ga_client = ga_client
service.page_category = params[:page_category]
service.via = "web"
begin
service.save!
flash[:notice] = t("messages._common.post")
redirect_to review_path(current_user.username, @review)
rescue
store_page_params(work: @work)
render :new
end
end
def edit(id)
@review = current_user.reviews.published.find(id)
authorize @review, :edit?
store_page_params(work: @work)
end
def update(id, review)
@review = current_user.reviews.published.find(id)
authorize @review, :update?
@review.attributes = review
@review.detect_locale!(:body)
@review.modified_at = Time.now
current_user.setting.attributes = setting_params
begin
ActiveRecord::Base.transaction do
@review.save!
current_user.setting.save!
end
if current_user.setting.share_review_to_twitter?
ShareReviewToTwitterJob.perform_later(current_user.id, @review.id)
end
if current_user.setting.share_review_to_facebook?
ShareReviewToFacebookJob.perform_later(current_user.id, @review.id)
end
flash[:notice] = t("messages._common.updated")
redirect_to review_path(@review.user.username, @review)
rescue
store_page_params(work: @work)
render :edit
end
end
def destroy(id)
@review = current_user.reviews.published.find(id)
authorize @review, :destroy?
@review.destroy
flash[:notice] = t("messages._common.deleted")
redirect_to work_reviews_path(@review.work)
end
private
def load_user
@user = User.find_by!(username: params[:username])
end
def load_review
@review = @user.reviews.published.find(params[:id])
end
def setting_params
params.require(:setting).permit(:share_review_to_twitter, :share_review_to_facebook)
end
end
|
class Review < ActiveRecord::Base
validates :author_id, :book_id, :rating, :title, presence: true
validates :author_id, uniqueness: { scope: :book_id }
belongs_to :user, foreign_key: :author_id
belongs_to :book
end
|
class AddSequenceToWesellItems < ActiveRecord::Migration
def change
add_column :wesell_items, :sequence, :integer, default: 100, null: false
end
end
|
class CreateEasyQuery < ActiveRecord::Migration
def self.up
create_table :easy_queries, :force => true do |t|
t.integer :project_id
t.string :name, :default => '', :null => false
t.text :filters
t.integer :user_id, :default => 0, :null => false
t.integer :visibility, :default => 0
t.text :column_names
t.text :sort_criteria
t.string :group_by
t.string :type
end
end
def self.down
drop_table :easy_queries
end
end
|
require 'spec_helper'
describe Api::V1::EtfsController do
describe "GET index" do
context "logged out" do
it "doesn't return anything" do
get :index
expect(response.response_code).to eql(401)
end
end
context "logged in" do
before(:each) do
@user = create(:user)
@e = create(:etf)
Api::V1::EtfsController.any_instance.stub(:current_user).and_return(@user)
end
it "returns all EF's" do
get :index
expect(response.response_code).to eql(200)
j = JSON.parse(response.body)
j.should include('etfs')
j['etfs'].should be_a(Array)
expect(j['etfs'][0]['id']).to eql(@e.id)
end
end
end
end
|
require 'spec_helper'
describe Lug::Device do
before do
@io = StringIO.new
end
describe '#initialize' do
it 'creates a device with stderr as default IO' do
device = Lug::Device.new
assert_equal STDERR, device.io
end
it 'accepts an optional +io+ parameter' do
device = Lug::Device.new(@io)
assert_equal @io, device.io
end
it 'calls #enable with DEBUG env variable if set' do
ENV['DEBUG'] = 'foo'
device = Lug::Device.new
assert device.enabled_for?(:foo)
refute device.enabled_for?(:bar)
end
end
describe '#log' do
before do
@device = Lug::Device.new(@io)
end
it 'logs message' do
Timecop.freeze(Time.now) do
@device.log('my message')
assert_equal "#{Time.now} #{$$} my message\n", @io.string
end
end
it 'logs message with namespace' do
Timecop.freeze(Time.now) do
@device.log('my message', :main)
assert_equal "#{Time.now} #{$$} [main] my message\n", @io.string
end
end
end
describe '#on' do
it 'creates a Logger thats wraps device with +namespace+' do
device = Lug::Device.new(@io)
logger = device.on(:script)
assert_instance_of Lug::Logger, logger
assert_equal device, logger.device
assert_equal 'script', logger.namespace
end
end
describe '#<<' do
it 'is an alias of #log' do
device = Lug::Device.new(@io)
device.log 'message'
res_log = @io.string
@io.truncate(0)
device << 'message'
res = @io.string
assert_equal res_log, res
end
end
end
|
class Generator
CHR_INDENT = 65
ALPHABET_SIZE = 26
CHR_RANDOM_LENGTH = 5
RANDOM_HASH_OPTIONS = 3
MAX_HASH_LENGTH = 5
MAX_NUMBER_VALUES = 1000
def initialize
@number = 0
end
#вывод хеша
def print_hash(hash = generate_hash, i = 0)
print '{'
hash.each_pair do |key, value|
puts "#{' '*i}'#{key}' => #{(value.is_a?(Hash) ? '{' : value.to_s) }#{(value.is_a?(Hash) ? '' : ',')}"
print_hash(value, i + 2) if value.is_a?(Hash)
puts "#{' '*i}}," if value.is_a?(Hash)
end
print '}'
end
private
#генерация рандомного символа
def rand_string
@number += 1
(0..(rand(CHR_RANDOM_LENGTH) + 1)).map { (CHR_INDENT + rand(ALPHABET_SIZE)).chr }.join.to_sym
end
#генерация рандомного варианта для значения хеша
def rand_option
rand(RANDOM_HASH_OPTIONS )
end
#генерация хеша
def generate_hash
step = 0
result_hash = {}
until (step > rand(MAX_HASH_LENGTH)) && (@number < MAX_NUMBER_VALUES)
case rand_option
when 1
random_value = rand(100)
when 2
random_value = nil
else
random_value = Hash[generate_hash]
end
result_hash[rand_string] = random_value
step += 1
end
result_hash
end
end
Generator.new.print_hash |
#!/usr/bin/env ruby
#
# top-fans will take a stdin list of collapsed graphs (see note-collapse)
# read through the posts, and then print out the top rebloggers
# and fans from all those in stdin.
#
# By using stdin, this allows one to read over multiple blogs.
#
require 'rubygems'
require 'bundler'
Bundler.require
$start = Time.new
header = true
if ARGV.length > 0
header = false
end
count = 0
limit = (ARGV[0] || 25).to_i
whoMap = {}
likeMap = {}
reblogMap = {}
$stdin.each_line { | file |
file = file.strip!
count += 1
if count % 200 == 0
$stderr.putc "."
end
File.open(file, 'r') { | content |
begin
reblog, likes = JSON.parse(content.read)
reblog.values.each { | tuple |
tuple.each { | who, post |
whoMap[who] = 1 + (whoMap[who] || 0)
reblogMap[who] = 1 + (reblogMap[who] || 0)
}
}
likes.each { | who |
whoMap[who] = 1 + (whoMap[who] || 0)
likeMap[who] = 1 + (likeMap[who] || 0)
}
rescue
end
}
}
top = [whoMap, likeMap, reblogMap].map { | which |
which.sort_by { | who, count | count }.reverse[0..limit]
}.transpose
if header
printf "\n %-31s %-30s %s\n", "total", "likes", "reblogs"
top.each { | row |
row.each { | who, count |
printf "%5d %-25s", count, who
}
printf "\n"
}
else
top.each { | row |
print "#{row[0][0]}.tumblr.com\n"
}
end
|
class UsersController < ApplicationController
layout 'boxed'
before_filter :select_user , :only =>[:edit,:update,:show,:destroy]
def new
@user = User.new
end
def create
@user = User.new(params[:user])
@user.admin = true if User.count==0 #make the first user admin
if @user.save
created_message(@user)
redirect_to root_url
else
render :action => 'new'
end
end
def edit
fail User::PermissionDenied unless @user.can_be_updated?(current_user)
end
def update
fail User::PermissionDenied unless @user.can_be_updated?(current_user)
if @user.update_attributes(params[:user])
updated_message(@user)
redirect_to @user
else
render :action => 'edit'
end
end
def show
render
end
def index
@users=User.all(:order => "points desc")
end
def destroy
deleted_message(@user)
@user.destroy
redirect_to users_url
end
private
def select_user
@user = User.find(params[:id])
end
end
|
class AddInstagramColumnsToSmData < ActiveRecord::Migration
def change
add_column :sm_data, :inst_id, :string
add_column :sm_data, :inst_followed_by, :integer
add_column :sm_data, :inst_follows, :integer
add_column :sm_data, :inst_hash_tag, :string
add_column :sm_data, :inst_tag_media_count, :integer
end
end
|
class ProvidersController < ApplicationController
def show
@provider = Provider.find(params[:id])
end
end
|
require 'rails_helper'
RSpec.describe TopicsController, type: :controller do
before(:all) do
@admin_user = User.create(username: "admin_user", email: "admin@gmail.com", password: "password", role: "admin")
@user = User.create(username: "own", email: "own@gmail.com", password: "password")
@topic = Topic.create(title: "TopicTitle", description: "TopicDescription TDD testing", user_id: "1")
end
describe "index" do
it "should render index" do
get :index
expect(subject).to render_template(:index)
end
end
describe "new topic" do
it "should deny if not logged in" do
get :new
expect(flash[:danger]).to eql("You need to login first")
end
it "should render new for admin" do
get :new, params: nil, session: { id: @admin_user.id }
expect(subject).to render_template(:new)
end
it "should deny user" do
cookies.signed[:id] = @user.id
get :new, params: nil
expect(flash[:danger]).to eql("You need to login first")
end
end
describe "create" do
it "should redirect if not logged in" do
params = { topic: { title: "NewTopicTitle", description: "NewTopicDescription" }}
post :create, params: params
expect(subject).to redirect_to(root_path)
expect(flash[:danger]).to eql("You need to login first")
end
# it "should deny if not logged in" do
# params = { topic: { title: "NewTopicTitle", description: "NewTopicDescription" } }
# post :create, params: params
#
# expect(flash[:danger]).to eql("You need to login first")
# end
it "should create new topic for admin" do
params = { topic: { title: "NewTitle", description: "New TitleDescription TDD testing" } }
post :create, params: params, session: { id: @admin_user.id }
topic = Topic.find_by(title: "NewTitle")
expect(Topic.count).to eql(2)
expect(topic).to be_present
expect(topic.description).to eql("New TitleDescription TDD testing")
expect(subject).to redirect_to(topics_path)
end
end
describe "edit topic" do
it "should redirect if not logged in" do
user_id = { id: @user.id }
get :edit, params: user_id
expect(subject).to redirect_to(root_path)
expect(flash[:danger]).to eql("You need to login first")
end
it "should redirect if user unauthorized" do
params = { id: @admin_user.id }
get :edit, params: params, session: { id: @user.id }
expect(subject).to redirect_to(root_path)
expect(flash[:danger]).to eql("You're not authorized")
end
it "should render edit" do
params = { id: @admin_user.id }
get :edit, params: params, session: { id: @admin_user.id }
current_user = subject.send(:current_user)
expect(subject).to render_template(:edit)
expect(current_user).to be_present
end
end
describe "update topic" do
it "should redirect if not logged in" do
params = { id: @topic.id, topic: { title: "NewTopic", description: "New TopicDescription TDD testing"} }
patch :update, params: params
expect(subject).to redirect_to(root_path)
expect(flash[:danger]).to eql("You need to login first")
end
it "should redirect if user unauthorized" do
params = { id: @topic.id, topic: { title: "NewTopic", description: "New TopicDescription TDD testing"} }
patch :update, params: params, session: { id: @user.id }
expect(subject).to redirect_to(root_path)
expect(flash[:danger]).to eql("You're not authorized")
end
it "should update topic" do
params = { id: @topic.id, topic: { title: "NewTopic", description: "New TopicDescription TDD testing"} }
patch :update, params: params, session: { id: @admin_user.id }
@topic.reload
expect(@topic.title).to eql("NewTopic")
expect(@topic.description).to eql("New TopicDescription TDD testing")
end
end
describe "destroy topic" do
it "should redirect if not logged in" do
params = { id: @user.id }
get :destroy, params: params
expect(subject).to redirect_to(root_path)
expect(flash[:danger]).to eql("You need to login first")
end
it "should redirect if user unauthorized" do
params = { id: @admin_user.id }
get :destroy, params: params, session: { id: @user.id }
expect(subject).to redirect_to(root_path)
expect(flash[:danger]).to eql("You're not authorized")
end
it "should render destroy" do
params = { id: @admin_user.id }
get :destroy, params: params, session: { id: @admin_user.id }
current_user = subject.send(:current_user)
expect(subject).to redirect_to(topics_path)
expect(current_user).to be_present
end
end
end
|
class CreateBlogs < ActiveRecord::Migration
def change
create_table :blogs do |t|
t.string :name
t.text :description, :feed
t.string :url, :feed_url
t.timestamp :feed_updated_at, :last_spidered
t.timestamps
end
end
end
|
class PetsController < ApplicationController
before_action :set_pet, only: [:show, :edit, :update, :destroy]
before_action :admin?, only: [:index]
def index
@pets = Pet.all
end
def new
@pet = Pet.new
@pet[:group_id] = params[:group_id]
end
def create
@pet = Pet.new(pet_params)
if @pet.save
redirect_to pet_path(@pet.id), notice: "ペットを登録しました!"
else
render :new
end
end
def show
@comments = @pet.comments
@comment = @pet.comments.build
end
def edit
end
def update
if @pet.update(pet_params)
redirect_to pets_path, notice: "編集しました!"
else
render :edit
end
end
def destroy
@pet.destroy
redirect_to pets_path, notice:"削除しました!"
end
private
def pet_params
params.require(:pet).permit(:id,:name, :birthday, :gender, :species, :icon, :icon_cache, :memo, :group_id)
end
def set_pet
@pet = Pet.find(params[:id])
end
def admin?
current_user.admin?
end
end
|
# frozen_string_literal: true
module Mutations
module Destroy
class User < ::Mutations::Destroy::Base
argument :id, !types.Int, 'ID of the user getting updated or deleted'
description 'Update a member status'
type ::Types::UserType
def call(_obj, args, ctx)
user = ::User.find args[:id]
destroy_generic user, ctx
end
end
end
end
|
# encoding: utf-8
#
control "V-94843" do
title "The Red Hat Enterprise Linux operating system must be configured so that the x86 Ctrl-Alt-Delete key sequence is disabled in the GUI."
desc "A locally logged-on user who presses Ctrl-Alt-Delete, when at the console, can reboot the system. If accidentally pressed, as could happen in the case of a mixed OS environment, this can create the risk of short-term loss of availability of systems due to unintentional reboot. In the GNOME graphical environment, risk of unintentional reboot from the Ctrl-Alt-Delete sequence is reduced because the user will be prompted before any action is taken."
impact 0.5
tag "check": "Verify the operating system is not configured to reboot the system when Ctrl-Alt-Delete is pressed.
Check that the ctrl-alt-del.target is masked and not active in the GUI with the following command:
# grep logout /etc/dconf/local.d/*
logout=''
If 'logout' is not set to use two single quotations, or is missing, this is a finding."
tag "fix": "Configure the system to disable the Ctrl-Alt-Delete sequence for the GUI with the following command:
# touch /etc/dconf/db/local.d/00-disable-CAD
Add the setting to disable the Ctrl-Alt-Delete sequence for GNOME:
[org/gnome/settings-daemon/plugins/media-keys]
logout=''"
if package('gnome-desktop3').installed?
describe command('grep logout /etc/dconf/local.d/*') do
its('stdout') { should eq 'logout='''}
end
else
describe "The system does not have GNOME installed" do
skip "The system does not have GNOME installed, this requirement is Not
Applicable."
end
end
end
|
class WinesController < ApplicationController
before_action :require_login
def new
#new for regular and nested route
if params[:country_id] && country = Country.find_by_id(params[:country_id])
@wine = country.wines.build
else
@wine = Wine.new
@wine.build_country
end
end
# def show
# @wine = Wine.find(params[:id])
# if params[:country_id] && params[:country_id].to_i != @wine.country_id
# redirect_to countries_path
# end
# end
def show
@wine = Wine.find(params[:id])
respond_to do |format|
format.html { render :show }
format.json { render json: @wine, status: 200 }
end
end
def create
@wine = current_user.wines.build(wine_params)
if @wine.save
render json: @wine, status: 201
else
render json: {errors: @wine.errors.full_messages}
end
end
def edit
@wine = Wine.find(params[:id])
if @wine.user_id != current_user.id
flash[:error] = "Sorry, you can only edit wines in your cellar."
redirect_to home_path
end
end
def update
@wine = Wine.find(params[:id])
if @wine.user_id != current_user.id
flash[:error] = "Sorry, you can only edit wines in your cellar."
redirect_to home_path
end
if @wine.update(wine_params)
redirect_to wine_path(@wine)
else
render :edit
end
end
def destroy
@wine = Wine.find(params[:id])
@wine.destroy
redirect_to root_path
end
private
def wine_params # strong parameters
params.require(:wine).permit(:picture, :varietal_id, :producer, :wine_name, :wine_type,
:country_id, :price_range, :user_id, :vintage, :rating, :notes, :favorite, :checkbox_value, aroma_ids:[],
tasting_term_ids:[], varietal_attributes: [:varietal_name], country_attributes: [:country_name])
end
end
|
feature "Sign up" do
scenario "signs up and increases maker count by 1" do
expect{sign_up}.to change(Maker, :count).by(1)
expect(current_path).to eq('/sessions')
end
end
|
class Admin::AdminsController < ApplicationController
def new
@admin = Admin.new
authorize @admin
if params[:user_id]
@admin.user = User.find(params[:user_id])
end
end
def create
user = params.require(:admin).require(:user_id)
user = User.find user
@admin = Admin.new(user: user)
authorize @admin
if @admin.save
redirect_to @admin.user, notice: 'User successfully promoted.'
return
end
redirect_to @admin.user, alert: 'Error while promoting user.'
end
def destroy
if params[:user_id]
@admin = User.find(params[:user_id]).as_admin
raise ActiveRecord::RecordNotFound if @admin.nil?
else
@admin = Admin.find params[:id]
end
authorize @admin
if request.delete?
user = @admin.user
@admin.destroy
redirect_to user, notice: 'User successfully demoted.'
end
end
end
|
module Validator
# = Validator::Folder
# Validates the folder id
class Folder < ActiveModel::Validator
TRANSLATION_SCOPE = [:errors, :messages]
def validate(record)
return false if record.folder_id.nil?
if record.respond_to?(:site)
if record.site.nil? || record.site.folders.nil?
record.errors[:base] << I18n.t(:folder,
:scope => TRANSLATION_SCOPE)
end
else
if ::Folder.find_by_id(record.folder_id).nil?
record.errors[:base] << I18n.t(:folder,
:scope => TRANSLATION_SCOPE)
end
end
end
end
end
|
class AddLastNameToUser < ActiveRecord::Migration
def change
add_column :users, :sn, :string
ldap = LdapQuery.new( :admin=> true )
users = User.all
users.each{|user|
if user.sn.nil?
user.ldap_verify
user.save
end
}
end
end
|
require_relative 'Fenetre'
class FenetreChargement < Fenetre
@boutonPrecedent
attr_reader :boutonPrecedent
public_class_method :new
# Fenetre affichant dynamiquement les boutons de reprise d'une partie sauvegardé.
#
# * *Args* :
# - +tabSave+ -> Matrice ou sont contenue les sauvegardes.
# - +jeu+ -> Session de jeu actuel du joueur
# - +estEdition+ -> Booleen pour savoir si on est en mode edition ou pas.
#
def initialize(tabSave,jeu,estEdition)
super()
@fenetre.set_title("Chargement de partie")
@fenetre.set_window_position(Gtk::Window::POS_CENTER)
@boutonPrecedent = Gtk::Button.new('Precedent')
@boutonPrecedent.set_size_request(-1, 50)
@boutonPrecedent.signal_connect('clicked'){
puts "> Accueil"
EcranAccueil.new(jeu, position())
@fenetre.hide_all()
}
@tabBouton = Array.new()
if(tabSave[estEdition] != nil)
0.upto(tabSave[estEdition].size()-1) do |i|
@tabBouton.push(Gtk::Button.new("Sauvegarde numero #{i}"))
end
0.upto(tabSave[estEdition].size()-1) do |i|
@tabBouton[i].signal_connect('clicked'){
jeu = ControleurPartie.Creer(tabSave[estEdition][i],nil,jeu,estEdition)
if(estEdition == 1)then
jeu.uneVue.timer = Timer.new()
else
jeu.uneVue.timer.tempsAccumule = tabSave[estEdition][i].timer
jeu.uneVue.timerFin.tempsAccumule = tabSave[estEdition][i].timer
end
jeu.uneVue.grille.afficherGrilleSolu()
@fenetre.hide_all
}
end
end
#A modifier
vBox = Gtk::VBox.new(false, 0)
vBox.set_border_width(5)
0.upto(@tabBouton.size()-1) do |i|
vBox.pack_start(@tabBouton[i], true, true, 0)
end
vBox.pack_end(@boutonPrecedent, false, true, 0)
@fenetre.add(vBox)
@fenetre.show_all
end
end
|
# What do you think the if does to the code under it?
# The if makes the code under it conditional or dependent on the if statement.
# Why does the code under the if need to be indented two spaces?
# The code needs to be indented to show what code is dependent on the if statement. For readability.
# What happens if it isn't indented?
# Nothing, it's just more difficult for the coder to see what's going on.
# Can you put other boolean expressions from Exercise 27 in the if-statement? Try it.
# Yes, you can. EX:
dogs = 30
if dogs != 30
puts "Not enough dogs."
else puts "Good amount of dogs."
end
# What happens if you change the initial values for people, cats, and dogs?
# It will change the output depending on if the new if statements return true or false.
|
class AddCueWordToDadJokes < ActiveRecord::Migration[6.0]
def change
add_column :dad_jokes, :cue_word, :string
add_index :dad_jokes, [:cue_word, :joke], unique: true
end
end
|
class Spree::IngramProductSetting < ActiveRecord::Base
has_one :product
attr_accessible :locked_fields, :last_updated_at, :keep_product, :product_id
attr_accessor :ignore_locks
def updated_recently
last_updated_at > 7.days.ago
end
def update_variant_info(isr, variant)
if isr.annotation.present?
variant.annotation = isr.annotation
end
unless locked?("price")
if isr.pub_list_price.to_f > 0.0
if variant.price
p = Spree::Price.where(variant_id: variant.id).first
p.amount = isr.pub_list_price.to_f
p.save
else
Spree::Price.create(variant_id: variant.id,
amount: isr.pub_list_price.to_f,
currency: Spree::Config[:currency])
end
end
end
unless locked?("discount")
variant.ingram_discount = isr.discount
variant.update_volume_discount(isr.publisher)
end
variant.height = isr.height.to_f > 0.0 ? isr.height.to_f + 1.0 : 9.1
variant.width = isr.width.to_f > 0.0 ? isr.width.to_f + 0.75: 5.1
variant.weight = isr.weight.to_f > 0.0 ? isr.weight.to_f + 0.25 : 1.21
variant.depth = isr.length.to_f > 0.0 ? isr.length.to_f + 0.25 : 1.1
variant.save
end
def update_product_info(isr)
unless locked?("title") or isr.title.size > 255
product.name = isr.title
end
unless locked?("image")
begin
io = open(isr.original_image_url, {:allow_redirections => :all, "User-Agent" => "Ruby-#{RUBY_VERSION}"})
rescue
io = nil
end
if io.present?
io.class_eval { attr_accessor :original_filename, :content_type }
io.content_type = "image/gif"
io.original_filename = isr.ean + ".gif"
unless io.size == 937
i = product.images.first
if i
i.attachment = io
i.save
else
Spree::Image.create(attachment: io, viewable_id: product.master.id, viewable_type: "product")
end
end
end
end
unless locked?("description")
product.description = isr._data_feed_description
end
self.last_updated_at = Time.current
self.save
product.save
end
def lock_array
locked_fields.split(", ")
end
def locked?(field_name)
# Ignoring the field lock is only for use while updating records through scripts
if ignore_locks
false
else
lock_array.include?(field_name)
end
end
def lock(field_name)
l = lock_array
unless l.include?(field_name)
l.push(field_name)
self.locked_fields = l.join(", ")
self.save
end
end
def unlock(field_name)
l = lock_array
if l.include?(field_name)
l.delete(field_name)
self.locked_fields = l.join(", ")
self.save
end
end
def self.lockable_fields
{
"discount" => "Discounts",
"price" => "Prices",
"image" => "Images",
"publish_date" => "Publish dates",
"title" => "Title",
"description" => "Description",
"categories" => "Category",
"authors" => "Authors",
"weight" => "Weight",
"height" => "Height",
"width" => "Width",
"length" => "Depth"
}
end
end
|
Pod::Spec.new do |s|
s.name = "Flurry"
s.version = "6.2.0"
s.homepage = "http://www.flurry.com/"
s.source = { :http => "http://repository.neonstingray.com/content/repositories/thirdparty/com/flurry/ios/flurry-analytic/6.2.0/flurry-analytic-6.2.0.zip" }
s.platform = :ios
s.frameworks = 'SystemConfiguration', 'Security'
s.xcconfig = { 'LIBRARY_SEARCH_PATHS' => '"$(PODS_ROOT)/Flurry"' }
s.preserve_paths = 'libFlurry_6.2.0.a'
s.source_files = '*.h'
s.libraries = 'Flurry_6.2.0'
end
|
require "test_helper"
describe ReviewsController do
let(:review) { reviews :one }
it "gets index" do
get reviews_url
value(response).must_be :successful?
end
describe "new" do
it "gets the form with the new review page" do
id = products(:cake1).id
get new_product_review_path(id)
value(response).must_be :successful?
end
end
describe "create" do
it "creates a new review given valid params" do
id = products(:cake1).id
review_hash = { review: { description: review.description, rating: review.rating} }
expect {
post product_reviews_path(id), params: review_hash
}.must_change "Review.count", 1
must_redirect_to product_path(id)
expect(Review.last.description).must_equal review_hash[:review][:description]
expect(Review.last.rating).must_equal review_hash[:review][:rating]
end
it "respond with an redirect for invalid params" do
id = products(:cake1).id
review_hash = { review: { description: review.description } }
expect {
post product_reviews_path(id), params: review_hash
}.wont_change "Review.count"
must_respond_with :success
expect(flash[:warning]).must_equal "Please enter all fields"
end
it "respond with an error if merchant reviews their own product" do
user = users(:laura)
perform_login(user)
id = products(:cake1).id
review_hash = { review: { description: review.description, rating: review.rating} }
expect {
post product_reviews_path(id), params: review_hash
}.wont_change "Review.count"
must_redirect_to products_path
expect(flash[:warning]).must_equal "You can't review your own Product"
end
end
end
|
require 'authenticate/login_status'
require 'authenticate/debug'
module Authenticate
# Represents an Authenticate session.
class Session
include Debug
attr_accessor :request
# Initialize an Authenticate session.
#
# The presence of a session does NOT mean the user is logged in; call #logged_in? to determine login status.
def initialize(request)
@request = request # trackable module accesses request
@cookies = request.cookie_jar
@session_token = @cookies[cookie_name]
debug 'SESSION initialize: @session_token: ' + @session_token.inspect
end
# Finish user login process, *after* the user has been authenticated.
# The user is authenticated by Authenticate::Controller#authenticate.
#
# Called when user creates an account or signs back into the app.
# Runs all configured callbacks, checking for login failure.
#
# If login is successful, @current_user is set and a session token is generated
# and returned to the client browser.
# If login fails, the user is NOT logged in. No session token is set,
# and @current_user will not be set.
#
# After callbacks are finished, a {LoginStatus} is yielded to the provided block,
# if one is provided.
#
# @param [User] user login completed for this user
# @yieldparam [Success,Failure] status result of the sign in operation.
# @return [User]
def login(user)
@current_user = user
@current_user.generate_session_token if user.present?
message = catch(:failure) do
Authenticate.lifecycle.run_callbacks(:after_set_user, @current_user, self, event: :authentication)
Authenticate.lifecycle.run_callbacks(:after_authentication, @current_user, self, event: :authentication)
end
status = message.present? ? Failure.new(message) : Success.new
if status.success?
@current_user.save
write_cookie if @current_user.session_token
else
@current_user = nil
end
yield(status) if block_given?
end
# Get the user represented by this session.
#
# @return [User]
def current_user
debug "session.current_user #{@current_user.inspect}"
@current_user ||= load_user_from_session_token if @session_token.present?
@current_user
end
# Has this user successfully logged in?
#
# @return [Boolean]
def logged_in?
debug "session.logged_in? #{current_user.present?}"
current_user.present?
end
# Invalidate the session token, unset the current user and remove the cookie.
#
# @return [void]
def logout
# nuke session_token in db
current_user.reset_session_token! if current_user.present?
# nuke notion of current_user
@current_user = nil
# nuke session_token cookie from the client browser
@cookies.delete cookie_name
end
private
def write_cookie
cookie_hash = {
path: Authenticate.configuration.cookie_path,
secure: Authenticate.configuration.secure_cookie,
httponly: Authenticate.configuration.cookie_http_only,
value: @current_user.session_token,
expires: Authenticate.configuration.cookie_expiration.call
}
cookie_hash[:domain] = Authenticate.configuration.cookie_domain if Authenticate.configuration.cookie_domain
# Consider adding an option for a signed cookie
@cookies[cookie_name] = cookie_hash
end
def cookie_name
Authenticate.configuration.cookie_name.freeze.to_sym
end
def load_user_from_session_token
Authenticate.configuration.user_model_class.where(session_token: @session_token).first
end
end
end
|
require 'rspec'
require 'rest_client'
require 'json'
require 'pathconfig'
require 'assert'
require 'topaz_token'
include Assert
include TopazToken
describe "follow_game" do
person_id = ""
people_activity_id = ""
follow_person_id = "10000"
verb = "FOLLOW"
actorType = "PERSON"
type = "Standard"
level = "New level achieved 2"
settings = true
#media_activity_id = ""
mediaItem_id = 65500
verb = "FOLLOW"
actorType = "PERSON"
wishList = false
released = true
unreleased = false
rating = "6"
accounts_id = "WII_ID"
accountType = "TOPAZ"
followableType = "PERSON"
gamerCard_type = "GAMER_CARD"
topaz_id = 0
testEmail =""
before(:all) do
PathConfig.config_path = File.dirname(__FILE__) + "/../../config/social.yml"
@config = PathConfig.new
@id = "#{Random.rand(60000000-900000000)}"
@nickname = "socialtesti2_#{Random.rand(200-9999)}"
@joined = "#{@nickname} joined the community"
TopazToken.set_token('social')
end
before(:each) do
end
after(:each) do
end
it "should register a new user" do
@time_stamp = Time.now.to_s
testEmail = "topaztulasi5_#{Random.rand(100-9999)}@ign.com"
@key1 = "102353737#{Random.rand(10-1000)}"
jdata = JSON.generate({"email"=> testEmail,"nickname"=>"#{@nickname}","accounts"=>[{"id"=> @id.to_i, "accountType"=>"topaz","key1"=> "#{@key1}","key2"=>"local"}]})
puts jdata
response = RestClient.post "http://#{@config.options['baseurl']}/v1.0/social/rest/reg",jdata, {:content_type => 'application/json'}
puts response.body
person_id= JSON.parse(response.body)["entry"][0]
end
it "should register in Topaz to get topaz Id", :test => true do
@profileId = "#{Random.rand(3000-40000000)}"
jdata = JSON.generate({"profileId" => person_id, "email" => testEmail, "provider" => "local", "password" => "test234"})
puts jdata
response = RestClient.post "http://secure-stg.ign.com/v3/authentication/user/register?oauth_token=#{TopazToken.return_token}", jdata, {:content_type => 'application/json'}
puts response.body
topaz_id = JSON.parse(response.body)["data"][0]["userId"]
puts topaz_id
end
it "should update the social service with the real topazID" do
jdata = JSON.generate({"accounts"=>[{"id" => @id.to_i,"accountType"=>"topaz","key1"=> topaz_id,"key2"=>"local"}]})
response = RestClient.put "http://#{@config.options['baseurl']}/v1.0/social/rest/people/#{person_id}", jdata, {:content_type => 'application/json'}
puts response.body
end
it "should get valid response for the new user with people/@self" do
sleep(5)
response = RestClient.get "http://#{@config.options['baseurl']}/v1.0/social/rest/people/nickname.#{@nickname}/@self"
response.code.should eql(200)
data = JSON.parse(response.body)
end
it "should get valid response for new user with topaz id" do
response = RestClient.get "http://#{@config.options['baseurl']}/v1.0/social/rest/people/topaz.#{topaz_id}/@self"
response.code.should eql(200)
end
it "should get valid response for new user with person id" do
response = RestClient.get "http://#{@config.options['baseurl']}/v1.0/social/rest/people/#{person_id.to_s}/@self"
response.code.should eql(200)
end
it "should check Get people/@self is not blank" do
response = RestClient.get "http://#{@config.options['baseurl']}/v1.0/social/rest/people/#{person_id.to_s}/@self"
data = JSON.parse(response.body)
check_not_blank(data)
end
it "should check get with topaz id is not blank" do
response = RestClient.get "http://#{@config.options['baseurl']}/v1.0/social/rest/people/topaz.#{topaz_id}/@self"
data = JSON.parse(response.body)
check_not_blank(data)
end
it "should check get with nickname is not blank" do
response = RestClient.get "http://#{@config.options['baseurl']}/v1.0/social/rest/people/nickname.#{@nickname}/@self"
data = JSON.parse(response.body)
check_not_blank(data)
end
it "should check for 4 indices" do
response = RestClient.get "http://#{@config.options['baseurl']}/v1.0/social/rest/people/nickname.#{@nickname}/@self"
data = JSON.parse(response.body)
check_indices(data, 4)
end
it "should check for 4 indices" do
response = RestClient.get "http://#{@config.options['baseurl']}/v1.0/social/rest/people/#{person_id.to_s}/@self"
data = JSON.parse(response.body)
check_indices(data, 4)
end
it "should check for 4 indices" do
response = RestClient.get "http://#{@config.options['baseurl']}/v1.0/social/rest/people/topaz.#{topaz_id}/@self"
data = JSON.parse(response.body)
check_indices(data, 4)
end
it "should match the settings fields" do
response = RestClient.get "http://#{@config.options['baseurl']}/v1.0/social/rest/people/nickname.#{@nickname}/@self"
data = JSON.parse(response.body)
settings.to_s.should eql (data["entry"][0]["settings"]["notifyOnReviewCommentReceived"])
settings.to_s.should eql (data["entry"][0]["settings"]["notifyOnWallPostReceived"])
settings.to_s.should eql (data["entry"][0]["settings"]["notifyOnBlogCommentReceived"])
settings.to_s.should eql (data["entry"][0]["settings"]["notifyOnFacebookFriendRegistered"])
settings.to_s.should eql (data["entry"][0]["settings"]["notifyOnFollowerReceived"])
settings.to_s.should eql (data["entry"][0]["settings"]["notifyOnDailyDigest"])
settings.to_s.should eql (data["entry"][0]["settings"]["notifyOnPrivateMessageReceived"])
settings.to_s.should eql (data["entry"][0]["settings"]["notifyOnLevelEarned"])
end
it "should match the type for people/@self" do
response = RestClient.get "http://#{@config.options['baseurl']}/v1.0/social/rest/people/nickname.#{@nickname}/@self"
data = JSON.parse(response.body)
settings.should eql (data["entry"][0]["accounts"][0]["isActive"])
person_id.should eql (data["entry"][0]["accounts"][0]["personId"])
accountType.to_s.should eql (data["entry"][0]["accounts"][0]["accountType"])
end
it "should match the nickname, followableType" do
response = RestClient.get "http://#{@config.options['baseurl']}/v1.0/social/rest/people/nickname.#{@nickname}/@self"
data = JSON.parse(response.body)
followableType.to_s.should eql (data["entry"][0]["followableType"])
@nickname.should eql (data ["entry"][0]["nickname"])
end
it "should get valid response for the new user with activities/@self" do
response = RestClient.get "http://#{@config.options['baseurl']}/v1.0/social/rest/activities/nickname.#{@nickname}/@self"
response.code.should eql(200)
data = JSON.parse(response.body)
end
it "should match the personId from new registration" do
response = RestClient.get "http://#{@config.options['baseurl']}/v1.0/social/rest/people/nickname.#{@nickname}/@self"
data = JSON.parse(response.body)
person_id.to_s().should eql(data["entry"][0]["id"])
end
it "should match the new level acheived" do
response = RestClient.get "http://#{@config.options['baseurl']}/v1.0/social/rest/activities/nickname.#{@nickname}/@self"
data = JSON.parse(response.body)
level.should eql(data["entry"][0]["body"])
@joined.should eql(data["entry"][1]["body"])
end
it "should follow the mediaItem" do
jdata = JSON.generate({"id"=>"65500"})
response = RestClient.post "http://#{@config.options['baseurl']}/v1.0/social/rest/mediaItems/#{person_id.to_s}/@self?st=#{person_id.to_s}:#{person_id.to_s}:0:ign.com:my.ign.com:0:0",jdata, {:content_type => 'application/json'}
mediaItem_activity_id= JSON.parse(response.body)["entry"]
#puts $mediaItem_activity_id
end
it "should return valid response code for mediaItem endpoint all" do
response = RestClient.get "http://#{@config.options['baseurl']}/v1.0/social/rest/mediaItems/#{person_id.to_s}/@self/@all"
response.code.should eql(200)
data = JSON.parse(response.body)
#puts "Verified that got valid response code"
end
it "should return valid response code for mediaItem wishlist" do
response = RestClient.get "http://#{@config.options['baseurl']}/v1.0/social/rest/mediaItems/#{person_id.to_s}/@self/@wishlist"
response.code.should eql(200)
data = JSON.parse(response.body)
end
it "should return valid response code for people collection" do
response = RestClient.get "http://#{@config.options['baseurl']}/v1.0/social/rest/mediaItems/#{person_id.to_s}/@self/@collection"
response.code.should eql(200)
data = JSON.parse(response.body)
end
it "should return valid response code for activities" do
response = RestClient.get "http://#{@config.options['baseurl']}/v1.0/social/rest/activities/#{person_id.to_s}/@self"
response.code.should eql(200)
data = JSON.parse(response.body)
end
it "should return the mediaItem with all" do
response = RestClient.get "http://#{@config.options['baseurl']}/v1.0/social/rest/mediaItems/#{person_id.to_s}/@self/@all"
data = JSON.parse(response.body)
mediaItem_id.should eql(data["entry"][0]["id"])
mediaItem_id.should eql(data["entry"][0]["mediaItemSetting"]["id"])
wishList.should eql(data["entry"][0]["mediaItemSetting"]["isWishList"])
released.should eql(data["entry"][0]["isReleased"])
puts "Verified that matches the mediaItemId in both entry and mediaItemSetting all"
end
it "should match the tags with collection" do
sleep(5)
response = RestClient.get "http://#{@config.options['baseurl']}/v1.0/social/rest/mediaItems/#{person_id.to_s}/@self/@collection"
data = JSON.parse(response.body)
mediaItem_id.should eql(data["entry"][0]["id"])
mediaItem_id.should eql(data["entry"][0]["mediaItemSetting"]["id"])
wishList.should eql(data["entry"][0]["mediaItemSetting"]["isWishList"])
released.should eql(data["entry"][0]["isReleased"])
puts "Verified that matches the mediaItemId in both entry and mediaItemSetting wishlist"
end
it "should match objectId, actorType and verb in activities" do
sleep(10)
response = RestClient.get "http://#{@config.options['baseurl']}/v1.0/social/rest/activities/#{person_id.to_s}/@self"
data = JSON.parse(response.body)
puts data["entry"][0]["activityObjects"][0]["objectId"].to_s
mediaItem_id.to_s.should eql(data["entry"][0]["activityObjects"][0]["objectId"].to_s)
verb.should eql(data["entry"][0]["verb"])
actorType.should eql(data["entry"][0]["actorType"])
puts "Verified that the objectId actorType and verb in activities"
end
it "should update the mediaItem" do
jdata = JSON.generate([{"id"=>"65500","isWishList" => "false", "showInNewsfeed"=> "true", "rating" => 6}])
response = RestClient.put "http://#{@config.options['baseurl']}/v1.0/social/rest/mediaItems/#{person_id.to_s}/@self?st=#{person_id.to_s}:#{person_id.to_s}:0:ign.com:my.ign.com:0:0",jdata, {:content_type => 'application/json'}
mediaItem_activity_id= JSON.parse(response.body)["entry"]
end
it "should match the mediaItemId, rating, wishlist the actor is following" do
response = RestClient.get "http://#{@config.options['baseurl']}/v1.0/social/rest/mediaItems/#{person_id.to_s}/@self/@all"
data = JSON.parse(response.body)
sleep(5)
mediaItem_id.should eql(data["entry"][0]["id"])
mediaItem_id.should eql(data["entry"][0]["mediaItemSetting"]["id"])
unreleased.should eql(data["entry"][0]["mediaItemSetting"]["isWishList"])
released.should eql(data["entry"][0]["isReleased"])
#rating.should eql(data["entry"][0]["userRating"])
puts "Verified that matches the tags the actor is following"
end
it "should unfollow the mediaitem" do
response = RestClient.delete "http://#{@config.options['baseurl']}/v1.0/social/rest/mediaItems/#{person_id.to_s}/@self/#{mediaItem_id}?st=#{person_id.to_s}:#{person_id.to_s}:0:ign.com:my.ign.com:0:0"
data = JSON.parse(response.body)
puts response.body
end
it "should delete the mediaItem from all" do
response = RestClient.get "http://#{@config.options['baseurl']}/v1.0/social/rest/mediaItems/#{person_id.to_s}/@self/@all"
data = JSON.parse(response.body)
0.should eql (data["totalResults"])
puts "Verified that the mediaItem is removed from all"
end
it "should delete mediaItem from wishlist" do
sleep(5)
response = RestClient.get "http://#{@config.options['baseurl']}/v1.0/social/rest/mediaItems/#{person_id.to_s}/@self/@wishlist"
data = JSON.parse(response.body)
0.should eql (data["totalResults"])
puts "Verified that the mediaItem is removed from wishlist"
end
it "should delete mediaItem from collection" do
sleep(5)
response = RestClient.get "http://#{@config.options['baseurl']}/v1.0/social/rest/mediaItems/#{person_id.to_s}/@self/@collection"
data = JSON.parse(response.body)
0.should eql (data["totalResults"])
puts "Verified that the mediaItem is removed from collection"
end
end
|
class AddEventTimesToFilms < ActiveRecord::Migration
def change
add_column :films, :average_sellout_minutes, :integer, index: true
add_column :screenings, :sale_began_at, :datetime
add_column :screenings, :soldout_at, :datetime
end
end
|
class AddCreatorToOrgas < ActiveRecord::Migration[5.0]
def change
add_reference :orgas, :creator, references: :users, index: true
end
end
|
require './lib/formats'
class FileCalculator
include Formats
def bytes_to_megabytes(bytes)
bytes / MEGABYTE
end
def gravity_of(extension)
all_formats.include?(extension) ? calculate(extension) : 1
end
def calculate(extension)
FORMATS.each do |format, weight|
return weight if format.include?(extension)
end
end
def weight(file)
file.extension == 'txt' ? add_weight(file) : multiply_weight(file)
end
def add_weight(file)
(file.size + file.gravity).round(2)
end
def multiply_weight(file)
(file.size * file.gravity).round(2)
end
end |
#
# Author:: Sergio Rua <sergio@rua.me.uk>
# Cookbook Name:: f5-bigip
# Provider:: ltm_node
#
# Copyright:: 2015 Sky Betting and Gaming
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
class Chef
class Provider
#
# Chef Provider for F5 LTM Node
#
class F5LtmAddressClass < Chef::Provider
include F5::Loader
# Support whyrun
def whyrun_supported?
false
end
def load_current_resource # rubocop:disable AbcSize, MethodLength
@current_resource = Chef::Resource::F5LtmAddressClass.new(@new_resource.name)
@current_resource.name(@new_resource.name)
@current_resource.sc_name(@new_resource.sc_name)
@current_resource.records(@new_resource.records)
Chef::Log.info("Changing partition to #{@new_resource.sc_name}")
load_balancer.change_folder(@new_resource.sc_name)
if @new_resource.sc_name.include?('/')
@current_resource.sc_name(@new_resource.sc_name.split('/')[2])
end
sc = load_balancer.client['LocalLB.Class'].get_address_class([@new_resource.sc_name]).find { |n| n['name'] == @new_resource.sc_name }
@current_resource.exists = !sc['members'].empty?
return @current_resource unless @current_resource.exists
members = []
sc.members.each do |m|
members << { 'address' => m.address, 'netmask' => m.netmask }
end
@current_resource.records(members)
@current_resource.update = members != @new_resource.records
@current_resource
end
def action_create
create_address_class unless current_resource.exists && !current_resource.update
end
def action_delete
delete_sc if current_resource.exists
end
private
#
# Create a new node from new_resource attribtues
#
def create_address_class # rubocop:disable AbcSize
converge_by("Create/Update data list #{new_resource}") do
Chef::Log.info "Create #{new_resource}"
new_sc = { 'name' => new_resource.sc_name, 'members' => new_resource.records }
if current_resource.update
load_balancer.client['LocalLB.Class'].modify_address_class([new_sc])
else
load_balancer.client['LocalLB.Class'].create_address_class([new_sc])
end
new_resource.updated_by_last_action(true)
end
end
#
# Delete node
#
def delete_sc
converge_by("Delete #{new_resource}") do
Chef::Log.info "Delete #{new_resource}"
load_balancer.client['LocalLB.Class'].delete_class([new_resource.sc_name])
new_resource.updated_by_last_action(true)
end
end
end
end
end
|
module Fog
module Compute
class Vsphere
class Real
def vm_config_vnc(options = { })
raise ArgumentError, "instance_uuid is a required parameter" unless options.key? 'instance_uuid'
search_filter = { :uuid => options['instance_uuid'], 'vmSearch' => true, 'instanceUuid' => true }
vm_mob_ref = connection.searchIndex.FindAllByUuid(search_filter).first
task = vm_mob_ref.ReconfigVM_Task(:spec => {
:extraConfig => [
{ :key => 'RemoteDisplay.vnc.enabled', :value => options[:enabled] ? 'true' : 'false' },
{ :key => 'RemoteDisplay.vnc.password', :value => options[:password].to_s },
{ :key => 'RemoteDisplay.vnc.port', :value => options[:port].to_s || '5910' }
]
})
task.wait_for_completion
{ 'task_state' => task.info.state }
end
# return a hash of VNC attributes required to view the console
def vm_get_vnc uuid
search_filter = { :uuid => uuid, 'vmSearch' => true, 'instanceUuid' => true }
vm = connection.searchIndex.FindAllByUuid(search_filter).first
Hash[vm.config.extraConfig.map do |config|
if config.key =~ /^RemoteDisplay\.vnc\.(\w+)$/
[$1.to_sym, config.value]
end
end.compact]
end
end
class Mock
def vm_config_vnc(options = { })
raise ArgumentError, "instance_uuid is a required parameter" unless options.key? 'instance_uuid'
{ 'task_state' => 'success' }
end
def vm_get_vnc uuid
{:password => 'secret', :port => '5900', :enabled => 'true'}
end
end
end
end
end
|
require_relative "card.rb"
require_relative 'hand_types/hand_type_mixins.rb'
filenames = %w(hand_type high_card pair three_of_a_kind four_of_a_kind two_pair straight flush full_house straight_flush)
filenames.each { |file| require_relative "hand_types/" + file + ".rb" }
class Hand
include Comparable, Descending_Order, Group_by_Value
def initialize(cards=[])
@cards = cards
@hand_type = update_hand_type
end
def cards
@cards.dup
end
def add(new_cards)
@cards += new_cards
update_hand_type
end
def discard(card)
raise "card not in hand" unless self.include?(card)
@cards.delete(card)
end
def include?(card)
cards.any? do |card_in_hand|
card_in_hand.value == card.value &&
card_in_hand.suit == card.suit
end
end
def <=>(other_hand)
@hand_type <=> other_hand.hand_type
end
def name
@hand_type.name
end
def to_s
@cards.map(&:to_s).join(", ")
end
protected
attr_reader :hand_type
private
def update_hand_type
if straight_flush?
@hand_type = Straight_Flush.new(cards)
elsif four_of_a_kind?
@hand_type = Four_of_a_Kind.new(cards)
elsif full_house?
@hand_type = Full_House.new(cards)
elsif flush?
@hand_type = Flush.new(cards)
elsif straight?
@hand_type = Straight.new(cards)
elsif three_of_a_kind?
@hand_type = Three_of_a_Kind.new(cards)
elsif two_pair?
@hand_type = Two_Pair.new(cards)
elsif pair?
@hand_type = Pair.new(cards)
else
@hand_type = High_Card.new(cards)
end
end
def straight_flush?
flush? && straight?
end
def flush?
cards.all? { |card| cards.first.suit == card.suit }
end
def straight?
descending_order.each_with_index do |card, i|
if i > 0
prev_val = descending_order[i-1].value_ranking
if card.value == :A
current_val = 1
else
current_val = card.value_ranking
end
unless prev_val == current_val + 1
return false
end
end
end
true
end
def four_of_a_kind?
group_by_value.any? { |group| group.length == 4 }
end
def three_of_a_kind?
group_by_value.any? { |group| group.length == 3 }
end
def pair?
group_by_value.count { |group| group.length == 2 } == 1
end
def two_pair?
group_by_value.count { |group| group.length == 2 } == 2
end
def full_house?
group_by_value.count { |group| group.length == 2 } == 1 &&
group_by_value.any? { |group| group.length == 3 }
end
end |
class ImagesController < ApplicationController
include ArticlesHelper
include Attribute::OpenAndCloseAt
skip_auth :index
PER_PAGE = 8
# GET :site/:folder/images/list
# = instace fields receiced to the view
# * @site
# * @folder
# * @articles
def list
@site = Site.find_by_name(params[:site])
if @site.nil?
return render_404
end
@folder = @site.folders.by_name(params[:folder]).first
if @folder.nil?
return render_404
end
@images = @folder.images.listing(@folder).page(params[:page]).per(PER_PAGE)
respond_to do |format|
format.html { render :action => :list}
end
end
# GET :site/images/selection_list
# GET :site/:folder/images/selection_list
# = instace fields receiced to the view
# * @site
# * @folder
# * @articles
def selection_list
@site = Site.find_by_name(params[:site])
if @site.nil?
return render_404
end
@folder =
unless params[:folder].blank?
@site.folders.by_id(params[:folder]).first or (render_404 and return)
end
@images =
if @folder
@folder.images.listing(@folder)
else
Image.editable_for(current_user)
end.page(params[:page]).per(PER_PAGE)
@folders =
if current_user.is_admin
@site.folders
else
Folder.editable_for(current_user)
end
respond_to do |format|
format.html { render :action => :selection_list, :layout => 'simple'}
end
end
# GET :site/:folder/images/new
# = instace fields receiced to the view
# * @site
# * @folder
# * @years
# * @months
# * @days
def new
@site = Site.find_by_name(params[:site])
if @site.nil?
return render_404
end
@folder = @site.folders.by_name(params[:folder]).first
if @folder.nil?
return render_404
end
@image = Image.new(:folder => @folder)
generate_selections!(@image)
respond_to do |format|
format.html
end
end
# GET :site/:folder/images/:id/edit
# = instace fields received to the view
# * @site
# * @folder
# * @years
# * @months
# * @days
def edit
@site = Site.find_by_name(params[:site])
if @site.nil?
return render_404
end
@folder = @site.folders.by_name(params[:folder]).first
if @folder.nil?
return render_404
end
@image = @folder.images.by_id(params[:id]).first
if @image.nil?
return render_404
end
generate_selections!(@image)
respond_to do |format|
format.html
end
end
# POST :site/:folder/images
def create
@site = Site.find_by_name(params[:site])
if @site.nil?
return render_404
end
@folder = @site.folders.by_name(params[:folder]).first
if @folder.nil?
return render_404
end
@image = Image.new(:folder => @folder)
@image.attributes = params[:image].permit(Image.accessible_attributes)
begin
@image.save!(:validate => true)
flash[:notice] = message(:images, :created)
return redirect_to :action => 'list'
rescue ActiveRecord::RecordInvalid => ex
generate_selections!(@image)
render :action => :new
end
end
# PUT :site/:folder/images/:id
def update
@site = Site.find_by_name(params[:site])
if @site.nil?
return render_404
end
@folder = @site.folders.by_name(params[:folder]).first
if @folder.nil?
return render_404
end
@image = @folder.images.by_id(params[:id]).first
if @image.nil?
return render_404
end
@image.attributes = params[:image].permit(Image.accessible_attributes)
begin
@image.save!(:validate => true)
flash[:notice] = message(:images, :updated)
return redirect_to :action => 'list'
rescue ActiveRecord::RecordInvalid => ex
generate_selections!(@image)
render :action => :edit
end
end
# DELETE :site/:folder/:id
def destroy
@site = Site.find_by_name(params[:site])
if @site.nil?
return render_404
end
@folder = @site.folders.by_name(params[:folder]).first
if @folder.nil?
return render_404
end
@image = @folder.images.by_id(params[:id]).first
begin
@image.destroy
flash[:notice] = message(:articles, :destroyed)
return redirect_to :action => 'list'
end
end
# get :site/:folder/images/:id
# get :site/:folder/images/:id/:style
# == requiest parameters
# * :site
# * :id
# * :style - original (default) | medium | small | thumb
def show
@site = Site.find_by_name(params[:site])
if @site.nil?
head(:not_found) and return
end
@folder = @site.folders.by_name(params[:folder]).first
if @folder.nil?
head(:not_found) and return
end
@image = @folder.images.by_id(params[:id]).first
if @image.nil?
return head(:not_found)
end
path = @image.image.path(params[:style])
p "file path = #{path}"
#unless File.exist?(path) && params[:format].to_s == File.extname(path).gsub(/^\.+/, '')
unless File.exist?(path)
head(:bad_request) and return
end
send_file_options = {:type => @image.image.content_type ,
:disposition => 'inline'
}
# case ::AppConfig::Application.instance.send_file_mathod
# when 'x_sendfile'; send_file_options[:x_sendfile] = true
# when 'x_accel_redirect' then
# head(:x_accel_redirect => path.gsub(Rails.root, ''), :content_type => send_file_options[:type]) and
# return
# end
send_file(path, send_file_options)
end
# PUT :site/:folder/images/:id/move_to_front (ajax)
# moves the article ahead
def move_ahead
@site = Site.find_by_name(params[:site])
if @site.nil?
return render_404
end
@folder = @site.folders.by_name(params[:folder]).first
if @folder.nil?
return render_404
end
@image = @folder.images.by_id(params[:id]).first
if @image.nil?
return render_404
end
begin
ActiveRecord::Base.transaction do
@image.move_ahead!
end
end
@images = @folder.images.listing(@folder).page(params[:page]).per(PER_PAGE)
respond_to do |format|
format.html { render :file => '/images/_image_table', :layout => false}
end
end
# PUT :site/:folder/images/:id/move_to_front (ajax)
# moves the article behind
def move_behind
@site = Site.find_by_name(params[:site])
if @site.nil?
return render_404
end
@folder = @site.folders.by_name(params[:folder]).first
if @folder.nil?
return render_404
end
@image = @folder.images.by_id(params[:id]).first
if @image.nil?
return render_404
end
begin
ActiveRecord::Base.transaction do
@image.move_behind!
end
end
@images = @folder.images.listing(@folder).page(params[:page]).per(PER_PAGE)
respond_to do |format|
format.html { render :file => '/images/_image_table', :layout => false}
end
end
private
# フォームでの選択肢となるコレクションの生成
def generate_selections!(image)
@years = years(image)
@months = months
@days = days
@hours = hours
@minutes = minutes
end
end
|
class Group < ActiveRecord::Base
has_one :profile, through: :account
belongs_to :account
has_many :members, dependent: :destroy
end
|
require_relative '../test_helper'
describe MySQLBinUUID::Type::Data do
it "is of kind ActiveModel::Type::Binary::Data" do
assert_kind_of ActiveModel::Type::Binary::Data, MySQLBinUUID::Type::Data.new(nil)
end
it "returns the raw value as hex value" do
assert_equal "e7db0d1a", MySQLBinUUID::Type::Data.new("e7db0d1a").hex
end
end
|
require 'rails_helper'
describe 'An admin' do
context 'visits station new' do
it 'can fill a form and click Create Station and is directed to station show page and see flash message' do
admin = create(:user, role: 1)
allow_any_instance_of(ApplicationController).to receive(:current_user).and_return(admin)
visit new_admin_station_path
fill_in :station_name, with: 'Pier 44'
fill_in :station_dock_count, with: 12
fill_in :station_city, with: 'Bellevue'
fill_in :station_installation_date, with: Time.now
click_button 'Create Station'
expect(current_path).to eq(station_path(Station.last))
expect(page).to have_content("#{Station.last.name} created!")
end
it 'cannot make a station with invalid inputs and sees flash message' do
admin = create(:user, role: 1)
allow_any_instance_of(ApplicationController).to receive(:current_user).and_return(admin)
visit new_admin_station_path
fill_in :station_name, with: 666
fill_in :station_dock_count, with: 'ghjk'
fill_in :station_city, with: nil
fill_in :station_installation_date, with: Time.now
click_button 'Create Station'
expect(page).to have_content("One of more fields are invalid")
end
end
end
|
class AddClanAndHandleToUsers < ActiveRecord::Migration[6.0]
def up
add_column :users, :clan, :string
add_column :users, :handle, :string
end
def down
remove_column :users, :clan
remove_column :users, :handle
end
end
|
class Author
attr_accessor :name
end
author = Author.new
|
class AddNewcolumnsToRestaurants < ActiveRecord::Migration
def change
add_column :restaurants, :gender, :string
add_column :restaurants, :year_graduated, :integer
add_column :restaurants, :title, :string
add_column :restaurants, :vendor_name, :string
add_column :restaurants, :vendor_type, :string
add_column :restaurants, :country, :string
add_column :restaurants, :contact1, :string
add_column :restaurants, :contact2, :string
add_column :restaurants, :biography, :string
add_column :restaurants, :website_address, :string
add_column :restaurants, :email, :string
add_column :restaurants, :fname, :string
add_column :restaurants, :lname, :string
add_column :restaurants, :password, :string
add_column :restaurants, :school, :string
add_column :restaurants, :degrees, :string
add_column :restaurants, :certifications, :string
add_column :restaurants, :specialities, :string
add_column :restaurants, :licence_no, :string
add_column :restaurants, :license_states, :string
add_column :restaurants, :cost, :float
add_column :restaurants, :average_cost, :float
add_column :restaurants, :accept_credit_card, :string
add_column :restaurants, :accept_insurance, :string
add_column :restaurants, :year_school, :string
add_column :restaurants, :accept_cash, :string
add_column :restaurants, :accept_check, :string
add_column :restaurants, :payment_plans, :string
add_column :restaurants, :work_hour, :string
add_column :restaurants, :p_address, :string
add_column :restaurants, :p_city, :string
add_column :restaurants, :p_state, :string
add_column :restaurants, :p_cell, :string
add_column :restaurants, :p_contact, :string
add_column :restaurants, :b_email, :string
add_column :restaurants, :p_country, :string
add_column :restaurants, :photo_file_name, :string
add_column :restaurants, :photo_content_type, :string
add_column :restaurants, :photo_file_size, :integer
end
end
|
class Order
attr_reader :book, :reader, :date
attr_accessor :library
def initialize (book, reader, date)
@book = book
@reader = reader
@date = date
end
def library=(lib)
if @library != lib # setting to new lib
@library.orders.delete(self) if @library # delete me from previous lib
@library = lib
@library.add_order self # add to new lib
end
end
def to_s
"#{super}: #{@reader} ordered #{@book} [#{@date}]"
end
alias_method :inspect, :to_s
def similar
if @library
@library.orders.select {|o| o.book == @book && o.reader == @reader }
end
end
end
|
json.data do |data|
data.array!(@member) do |member|
json.partial! '/bold/v1/partials/members', member: member
end
end |
namespace :generate_admin_app do
desc "Auto generate data request state"
task admin_user: :environment do
User.create(name: "Admin", email: "admin@gmail.com", birthday: "20/11/1994", gender: "male", password: "123456", role: "admin")
end
end
|
require 'rails_helper'
RSpec.describe 'Book Show Page', type: :feature do
describe 'as a visitor visiting the books show page' do
before :each do
@book_1 = Book.create!(title: "The Hobbit")
@user_1 = User.new(name: "Tom")
@user_2 = User.new(name: "Jerry")
@review_1 = @book_1.reviews.create!(rating: 5, content: "Really Good", user: @user_1)
@review_2 = @book_1.reviews.create!(rating: 3, content: "Average Read", user: @user_2)
end
it 'shows the book title, list of reviews with - rating, content, user name' do
visit book_path(@book_1)
expect(page).to have_content(@book_1.title)
within "#review-#{@review_1.id}" do
expect(page).to have_content("Rating: #{@review_1.rating}")
expect(page).to have_content("Content: #{@review_1.content}")
expect(page).to have_content("User: #{@review_1.user.name}")
end
within "#review-#{@review_2.id}" do
expect(page).to have_content("Rating: #{@review_2.rating}")
expect(page).to have_content("Content: #{@review_2.content}")
expect(page).to have_content("User: #{@review_2.user.name}")
end
end
it 'shows the average rating for the book' do
visit book_path(@book_1)
expect(page).to have_content("Average Rating: #{@book_1.average_rating}")
end
it 'shows the highest rating for the book, along with the review text and name of reviewer' do
visit book_path(@book_1)
within "#top-review" do
expect(page).to have_content("Top Rating: #{@book_1.top_review.rating}")
expect(page).to have_content("Content: #{@book_1.top_review.content}")
expect(page).to have_content("User: #{@book_1.top_review.user.name}")
end
end
it 'shows the highest rating for the book, along with the review text and name of reviewer' do
visit book_path(@book_1)
within "#worst-review" do
expect(page).to have_content("Worst Rating: #{@book_1.worst_review.rating}")
expect(page).to have_content("Content: #{@book_1.worst_review.content}")
expect(page).to have_content("User: #{@book_1.worst_review.user.name}")
end
end
end
end
|
module TheCityAdmin
class MetricMeasurement < ApiObject
tc_attr_accessor :id,
:created_at,
:value
# Constructor.
#
# @param json_data JSON data of the role.
def initialize(json_data)
initialize_from_json_object(json_data)
end
# Save this object.
#
# @return True on success, otherwise false.
def save
writer = MetricMeasurementWriter.new(self.to_attributes)
writer.save_feed
end
end
end
|
class UserSerializer < ApplicationSerializer
identifier :id
view :show do
fields :email, :profile_type
association :profile, blueprint: ->(profile) { profile.serializer }
end
view :create do
include_view :show
field :token do |user, options|
options[:token]
end
end
# NOTE: It is the same as the show action for now, but here is a separate view for later use
view :update do
include_view :show
exclude :token
end
end
|
require_relative '../../spec_helper'
describe BandCampBX::Mapper do
subject(:mapper) { described_class.new }
let(:json_object){ '{"foo": "bar"}' }
let(:json_array){ '[{"foo": "bar"}]' }
describe '#map_balance' do
let(:balance) { double }
before do
Entities::Balance.stub(:new).and_return(balance)
end
it "maps a balance API response into a Balance entity" do
mapper.map_balance(json_object)
expect(Entities::Balance).to have_received(:new).with(json_parse(json_object))
end
it "returns the mapped Balance entity" do
expect(mapper.map_balance(json_object)).to eq(balance)
end
end
describe '#map_order' do
let(:order) { double }
end
describe '#map_orders' do
let(:order) { double }
it "filters out empty results appropriately" do
empty_json = '{"Buy": [{"Info":"No open Buy Orders"}], "Sell": [{"Info":"No open Sell Orders"}]}'
expect(mapper.map_orders(empty_json)).to eq([])
end
it "returns an Order if mapped appropriately" do
Entities::Order.stub(:new).and_return(order)
expect(mapper.map_order(json_object)).to eq(order)
end
it "raises a StandardError if it doesn't know what to do with a mapping" do
expect{ mapper.map_order('{}') }.to raise_error(StandardError)
end
it "raises an InvalidTradeTypeError if that message comes back from the API" do
expect{ mapper.map_order('{"Error":"Invalid trade type."}') }.to raise_error(StandardError, "Invalid trade type.")
end
end
describe '#map_cancel' do
it "maps a cancel API response to a boolean" do
expect(mapper.map_cancel('"true"')).to eq(true)
expect(mapper.map_cancel('"false"')).to eq(false)
end
end
describe "#map_ticker" do
it "maps a ticker response to a JSON object" do
json_string = "{\"Last Trade\":\"143.23\",\"Best Bid\":\"142.92\",\"Best Ask\":\"143.99\"}"
json_object = {trade: 143.23, bid: 142.92, ask: 143.99}
expect(mapper.map_ticker(json_string)).to eq(json_object)
end
end
end
|
class Node
attr_accessor :value, :left, :right, :name
def initialize(options={})
@value = options[:value]
@name = options[:name]
end
def children
[@left, @right].compact
end
def children?
@left && @right
end
def no_children?
!children?
end
end
# Create nodes
root = Node.new({:value => 1, :name => "root"})
child_1 = Node.new({:value => 2, :name => "child_1"})
child_2 = Node.new({:value => 3, :name => "child_2"})
grand_child_1 = Node.new({:value => 4, :name => "grand_child_1"})
grand_child_2 = Node.new({:value => 5, :name => "grand_child_2"})
# Connect the nodes
child_1.left = grand_child_1
child_1.right = grand_child_2
root.left = child_1
root.right = child_2
def breath_first_search(node)
queue = []
queue.push(node)
while(queue.length != 0)
current = queue.shift
puts current.value
current.children.each do |child|
queue.push(child)
end
end
end
breath_first_search(root)
def depth_first_search(node)
puts node.value
node.children.each do |child|
depth_first_search(child)
end
end
depth_first_search(root)
|
class AddChecksumToReports < ActiveRecord::Migration
def change
add_column :reports, :checksum, :string
end
end
|
class Merb::Cache
cattr_accessor :cached_actions
self.cached_actions = {}
end
module Merb::Cache::ControllerClassMethods
# Mixed in Merb::Controller. Provides methods related to action caching
# Register the action for action caching
#
# ==== Parameters
# action<Symbol>:: The name of the action to register
# from_now<~minutes>::
# The number of minutes (from now) the cache should persist
#
# ==== Examples
# cache_action :mostly_static
# cache_action :barely_dynamic, 10
def cache_action(action, from_now = nil)
cache_actions([action, from_now])
end
# Register actions for action caching (before and after filters)
#
# ==== Parameter
# actions<Symbol,Array[Symbol,~minutes]>:: See #cache_action
#
# ==== Example
# cache_actions :mostly_static, [:barely_dynamic, 10]
def cache_actions(*actions)
if actions.any? && Merb::Cache.cached_actions.empty?
before(:cache_action_before)
after(:cache_action_after)
end
actions.each do |action, from_now|
_actions = Merb::Cache.cached_actions[controller_name] ||= {}
_actions[action] = from_now
end
true
end
end
module Merb::Cache::ControllerInstanceMethods
# Mixed in Merb::Controller. Provides methods related to action caching
# Checks whether a cache entry exists
#
# ==== Parameter
# options<String,Hash>:: The options that will be passed to #key_for
#
# ==== Returns
# true if the cache entry exists, false otherwise
#
# ==== Example
# cached_action?(:action => 'show', :params => [params[:page]])
def cached_action?(options)
key = Merb::Controller._cache.key_for(options, controller_name, true)
Merb::Controller._cache.store.cached?(key)
end
# Expires the action identified by the key computed after the parameters
#
# ==== Parameter
# options<String,Hash>:: The options that will be passed to #expire_key_for
#
# ==== Examples
# expire_action(:action => 'show', :controller => 'news')
# expire_action(:action => 'show', :match => true)
def expire_action(options)
Merb::Controller._cache.expire_key_for(options, controller_name, true) do |key, match|
if match
Merb::Controller._cache.store.expire_match(key)
else
Merb::Controller._cache.store.expire(key)
end
end
true
end
# You can call this method if you need to prevent caching the action
# after it has been rendered.
def abort_cache_action
@capture_action = false
end
private
# Called by the before and after filters. Stores or recalls a cache entry.
# The key is based on the result of request.path
# If the key with "/" then it is removed
# If the key is "/" then it will be replaced by "index"
#
# ==== Parameters
# data<String>:: the data to put in cache using the cache store
#
# ==== Examples
# If request.path is "/", the key will be "index"
# If request.path is "/news/show/1", the key will be "/news/show/1"
# If request.path is "/news/show/", the key will be "/news/show"
def _cache_action(data = nil)
controller = controller_name
action = action_name.to_sym
actions = Merb::Controller._cache.cached_actions[controller]
return unless actions && actions.key?(action)
path = request.path.chomp("/")
path = "index" if path.empty?
if data
from_now = Merb::Controller._cache.cached_actions[controller][action]
Merb::Controller._cache.store.cache_set(path, data, from_now)
else
@capture_action = false
_data = Merb::Controller._cache.store.cache_get(path)
throw(:halt, _data) unless _data.nil?
@capture_action = true
end
true
end
# before filter
def cache_action_before
# recalls a cached entry or set @capture_action to true in order
# to grab the response in the after filter
_cache_action
end
# after filter
def cache_action_after
# takes the body of the response and put it in cache
# if the cache entry expired, if it doesn't exist or status is 200
_cache_action(body) if @capture_action && status == 200
end
end
|
class AddLostDateToLostItems < ActiveRecord::Migration
def change
remove_column :lost_items, :lost_date
add_column :lost_items, :lost_date, :datetime
end
end
|
require 'test_helper'
class UrbanProjectTest < ActiveSupport::TestCase
def setup
@urban_project = UrbanProject.new
@urban_project.name = "lorem ipsum"
@urban_project.info = "lorem ipsum"
end
test "should not be valid without description" do
@urban_project.description = nil
assert_not @urban_project.valid?
end
test "urban project description should not be short" do
@urban_project.description = "a"*9
assert_not @urban_project.valid?
end
end
|
require 'rails_helper'
RSpec.describe "Users::Registrations", type: :request do
let(:user) { FactoryGirl.create(:user) }
describe "PUT /users/edit" do
it "updates user profile" do
login_as user
visit edit_user_registration_url
within ".edit_user" do
fill_in "Twitter", with: "rubyconftw"
click_button "Update User"
end
expect(page).to have_content("Your account has been updated successfully.")
end
it "didn't update user profile when not fill required fields" do
login_as user
visit edit_user_registration_url
within ".edit_user" do
fill_in "Name", with: ""
click_button "Update User"
end
expect(page).to have_css(".has-error")
end
end
end
|
class Instrument < ApplicationRecord
has_many :user_instruments
has_many :instruments, through: :user_instruments
end
|
require 'fog/hetznercloud/client'
require 'fog/hetznercloud/errors'
require 'fog/hetznercloud/request_helper'
module Fog
module Hetznercloud
class Compute < Fog::Service
class UnauthorizedError < Error; end
class ForbiddenError < Error; end
class InvalidInputError < Error; end
class JsonErrorError < Error; end
class LockedError < Error; end
class NotFoundError < Error; end
class RateLimitExceededError < Error; end
class ResourceLimitExeceededError < Error; end
class ResourceUnavailableError < Error; end
class ServiceErrorError < Error; end
class UniquenessErrorError < Error; end
class UnknownResourceError < Error; end
class StateError < Error; end
requires :hetznercloud_token
recognizes :hetznercloud_datacenter
recognizes :hetznercloud_location
secrets :hetznercloud_token
model_path 'fog/hetznercloud/models/compute'
model :server
collection :servers
model :image
collection :images
model :server_type
collection :server_types
model :action
collection :actions
model :floating_ip
collection :floating_ips
model :location
collection :locations
model :datacenter
collection :datacenters
model :ssh_key
collection :ssh_keys
request_path 'fog/hetznercloud/requests/compute'
## Servers
request :create_server
request :list_servers
request :get_server
request :update_server
request :delete_server
request :execute_server_action
# Server Types
request :list_server_types
request :get_server_type
# Images
request :list_images
request :get_image
request :delete_image
request :update_image
# Actions
request :list_actions
request :get_action
# Locations
request :list_locations
request :get_location
# Datacenters
request :list_datacenters
request :get_datacenter
# Ssh Keys
request :list_ssh_keys
request :get_ssh_key
request :create_ssh_key
request :delete_ssh_key
request :update_ssh_key
# Floating IP'S
request :list_floating_ips
request :get_floating_ip
request :create_floating_ip
request :delete_floating_ip
request :update_floating_ip
request :floating_ip_assign_to_server
request :floating_ip_unassign
request :floating_ip_update_dns_ptr
class Real
include Fog::Hetznercloud::RequestHelper
# FIXME: Make @location and @datacenter used in server creation
# as default
def initialize(options)
@token = options[:hetznercloud_token]
@location = options[:hetznercloud_location] || 'fsn1'
@datacenter = options[:hetznercloud_datacenter] || 'fsn1-dc8'
@connection_options = options[:connection_options] || {}
end
def request(params)
client.request(params)
rescue Excon::Errors::HTTPStatusError => error
decoded = Fog::Hetznercloud::Errors.decode_error(error)
raise if decoded.nil?
code = decoded[:code]
message = decoded[:message]
raise case code
when 'unauthorized', 'forbidden', 'invalid_input', 'json_error', 'locked', 'not_found', 'rate_limit_exceeded', 'resource_limit_exceeded', 'resource_unavailable', 'service_error', 'uniqueness_error'
Fog::Hetznercloud::Compute.const_get("#{camelize(code)}Error").slurp(error, message)
else
Fog::Hetznercloud::Compute::Error.slurp(error, message)
end
end
private
def client
@client ||= Fog::Hetznercloud::Client.new(endpoint, @token, @connection_options)
end
def endpoint
'https://api.hetzner.cloud/'
end
def camelize(str)
str.split('_').collect(&:capitalize).join
end
end
class Mock
def request(*_args)
Fog::Mock.not_implemented
end
end
end
end
end
|
module Fog
module Compute
class Google
class TargetHttpsProxies < Fog::Collection
model Fog::Compute::Google::TargetHttpsProxy
def all(_filters = {})
data = service.list_target_https_proxies.to_h[:items] || []
load(data)
end
def get(identity)
if identity
target_https_proxy = service.get_target_https_proxy(identity).to_h
return new(target_https_proxy)
end
rescue ::Google::Apis::ClientError => e
raise e unless e.status_code == 404
nil
end
end
end
end
end
|
require 'rails_helper'
describe Ability do
subject(:ability) { Ability.new(user) }
describe 'for guest' do
let(:user) { nil }
it { should be_able_to :read, Question }
it { should be_able_to :read, Answer }
it { should be_able_to :read, Comment }
it { should be_able_to :search, :all }
it { should_not be_able_to :manage, :all }
end
describe 'for admin' do
let(:user) { create :user, admin: true }
it { should be_able_to :manage, :all }
it { should be_able_to :search, :all }
end
describe 'for user' do
let(:user) { create :user }
let(:other_user) { create :user }
let(:question_of_user) { create :question, user_id: user.id }
let(:question_of_other_user) { create :question, user_id: other_user.id }
let(:answer_of_user) { create :answer, user_id: user.id }
let(:answer_of_other_user) { create :answer, user_id: other_user.id }
let(:subscription_of_user) { create :subscription, user_id: user.id }
let(:subscription_of_other_user) { create :subscription, user_id: other_user.id }
it { should_not be_able_to :manage, :all }
it { should be_able_to :read, :all }
it { should be_able_to :search, :all }
it { should be_able_to :create, Question }
it { should be_able_to :create, Answer }
it { should be_able_to :create, Subscription }
it { should be_able_to :create_comment, Comment }
it { should be_able_to :update, question_of_user }
it { should_not be_able_to :update, question_of_other_user }
it { should be_able_to :update, answer_of_user }
it { should_not be_able_to :update, answer_of_other_user }
it { should be_able_to :destroy, question_of_user }
it { should_not be_able_to :destroy, question_of_other_user }
it { should be_able_to :destroy, answer_of_user }
it { should_not be_able_to :destroy, answer_of_other_user }
it { should be_able_to :destroy, subscription_of_user }
it { should_not be_able_to :destroy, subscription_of_other_user }
context 'Links' do
it { should be_able_to :destroy, create(:link, linkable: question_of_user) }
it { should_not be_able_to :destroy, create(:link, linkable: question_of_other_user) }
it { should be_able_to :destroy, create(:link, linkable: answer_of_user) }
it { should_not be_able_to :destroy, create(:link, linkable: create(:answer, user_id: other_user.id )) }
end
context "Attachments" do
it { should be_able_to :destroy, create(:question_with_attached_file, user_id: user.id).files.first }
it { should_not be_able_to :destroy, create(:question_with_attached_file, user_id: other_user.id).files.first }
it { should be_able_to :destroy, create(:answer_with_attached_file, user_id: user.id).files.first }
it { should_not be_able_to :destroy, create(:answer_with_attached_file, user_id: other_user.id).files.first }
end
context "Best answer" do
it { should be_able_to :best, create(:answer, question: question_of_user) }
it { should_not be_able_to :best, create(:answer, question: question_of_other_user) }
end
context 'Voting' do
it { should_not be_able_to [:like, :dislike, :unvote], create(:vote, votable: question_of_user) }
it { should be_able_to [:like, :dislike, :unvote], create(:vote, user_id: user.id,
votable: question_of_other_user) }
it { should_not be_able_to [:like, :dislike, :unvote], create(:vote, votable: answer_of_user) }
it { should be_able_to [:like, :dislike, :unvote], create(:vote, user_id: user.id,
votable: answer_of_other_user) }
it { should_not be_able_to :create_vote, create(:vote, votable: question_of_user) }
it { should be_able_to :create_vote, create(:vote, votable: question_of_other_user) }
end
end
end
|
require 'spec_helper'
feature "Shopping Cart" do
before do
DatabaseCleaner.clean
end
scenario 'guest user and logged in user can see items in the shopping cart' do
product = create_product
visit product_path(product)
click_on 'Add To Cart'
expect(page).to have_content 'My Cart'
expect(page).to have_content 'Great Gatsby'
expect(page).to have_content 'Total: $10.00'
# Button to add item to cart is replaced by text after item is added to cart
visit product_path(product)
expect(page).to have_content 'Item is already in your cart'
expect(page).to_not have_content 'Add To Cart'
end
end |
require 'rails_helper'
RSpec.describe MessagesController, type: :controller do
describe 'GET #index' do
let(:user) { create(:user) }
before do
sign_in(user)
get :index
end
it 'render index template' do
expect(response).to render_template :index
end
end
describe 'POST #create' do
let(:sender) { create(:user) }
let(:receiver) { create(:user) }
let(:other_conversation) { create(:conversation, sender: sender, receiver: receiver) }
context 'when authenticated user' do
before { sign_in(sender) }
it 'create message with conversation' do
expect do
post :create, params: { conversation_id: other_conversation, user_id: sender, body: '123' }, format: :js
end.to change(other_conversation.messages, :count)
end
it 'create message without conversation' do
expect do
post :create, params: { sender_id: sender, receiver_id: receiver, body: '123' }, format: :js
end.to change(Message, :count)
end
it 'is not create message with conversation' do
expect do
post :create, params: { conversation_id: other_conversation }, format: :js
end.not_to change(Message, :count)
end
it 'is not create message without conversation' do
expect do
post :create, params: { receiver_id: receiver, body: '123' }, format: :js
end.not_to change(Message, :count)
end
end
context 'when unauthenticated user' do
it 'create message with conversation' do
expect do
post :create, params: { conversation_id: other_conversation, user_id: sender, body: '123' }, format: :js
end.not_to change(other_conversation.messages, :count)
expect(response.status).to eq 401
end
it 'create message without conversation' do
expect do
post :create, params: { sender_id: sender, receiver_id: receiver, body: '123' }, format: :js
end.not_to change(Message, :count)
expect(response.status).to eq 401
end
end
end
end
|
#/lib/controller
require_relative 'player'
require_relative 'board'
require 'json'
class Controller
def initialize(player1 =nil, player2=nil,gameBoard=nil,current_turn=nil)
if(player1==nil)
@player1 = Player.new(getPlayerNames,"⚫")
@player2 = Player.new(getPlayerNames,"⚪")
@current_turn = player1
puts "Type save anytime to save the game, quit to quit"
@gameBoard = play_game(@player1, @player2)
else
puts "Welcome Back"
@player1 = player1
@player2 = player2
@gameBoard = gameBoard
@current_turn = current_turn
resume_game(@player1,@player2,@currentTurn,@gameBoard)
end
end
def to_json
JSON.dump ({
:player1 => @player1.to_json,
:player2 => @player2.to_json,
:gameBoard => @gameBoard.to_json,
:current_turn => @current_turn.to_json
})
end
def self.from_json(string)
data = JSON.load string
self.new(Player.from_json(data['player1']), Player.from_json(data['player2']),Board.from_json(data['gameBoard']), Player.from_json(data['current_turn']))
end
def resume_game(player1,player2,current_turn,board)
keep_playing = true
@gameBoard = board
while(keep_playing)
puts @gameBoard
if(current_turn == player1)
turn_switcher(player1 ,player2)
else
turn_switcher(player2 ,player1)
end
puts "#{player1.name} has won #{player1.wins} games"
puts "#{player2.name} has won #{player2.wins} games"
@gameBoard = Board.new()
puts "\nType yes to start a new game or any key to exit\n"
continue = gets.chomp.downcase
if continue != "yes"
quit()
end
end
end
def play_game(player1 ,player2)
keep_playing = true
while(keep_playing)
@gameBoard = Board.new()
puts @gameBoard
turn_switcher(player1 ,player2)
puts "#{player1.name} has won #{player1.wins} games"
puts "#{player2.name} has won #{player2.wins} games"
puts "\nType yes to start a new game or any key to exit\n"
continue = gets.chomp.downcase
if continue != "yes"
quit()
end
end
return @gameBoard.board
end
def quit()
puts "Thanks For Playing"
exit(0)
end
def make_move(player, messgage = "")
(messgage == "") ? (puts "#{player.name}(#{player.symbol}) Please Select a Column") : (puts messgage)
move_input = (gets.chomp)
if(['1','2','3','4','5','6','7']).include?(move_input)
if (@gameBoard.column_empty?(move_input.to_i))
@gameBoard.drop_element(player.symbol,move_input.to_i)
puts @gameBoard
else
make_move(player,"Sorry #{player.name} That Column is Full")
end
elsif(move_input.downcase == "save")
saveGame()
puts "game is saved"
quit()
elsif(move_input.downcase == "quit")
quit()
else
make_move(player,"That is Not a Valid Column Entry")
end
end
def getPlayerNames()
puts "Please enter a player name"
name = (gets.chomp)
return name
end
def turn_switcher(player1, player2)
while (@gameBoard.check_for_full_board() == false)
@current_turn = @player1
make_move(player1)
if(@gameBoard.check_win(player1))
puts "#{@player1.name} wins!\n"
@player1.award_win()
break
end
@current_turn = @player2
make_move (player2)
if(@gameBoard.check_win( player2))
player2.award_win()
puts "#{player2.name} wins!\n"
break
end
end
if(@gameBoard.check_for_full_board())
puts "Game Over: No one wins!\n"
end
end
def saveGame()
directory = "saves"
if (!File.directory?(directory))
Dir.mkdir(directory)
end
puts "Please enter a save file name"
filename = String.new
while((filename.match(/^[a-zA-Z0-9]+$/) == nil) )
filename = gets.chomp.downcase
if(File.exist?("../connect_four/saves/#{filename}.json"))
puts "That filename already exists please choose another"
filename = "-----"
end
if(filename.match(/^[a-zA-Z0-9]+$/) == nil)
puts "Invalid Input\nPlease Enter a valid Filename"
end
end
File.write("../connect_four/saves/#{filename}.json", self.to_json)
end
end
|
class CreateEngineerPersonInfos < ActiveRecord::Migration[5.2]
def change
create_table :engineer_person_infos,comment:EngineerPersonInfo.model_name.human do |t|
t.references :engineer, foreign_key: true
t.references :person_info, foreign_key: true
t.timestamps
end
end
end
|
module CRM
class Person
attr_accessor :name
end
end
|
class Auction < ApplicationRecord
belongs_to :user
has_many :bids, dependent: :destroy
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.