text stringlengths 10 2.61M |
|---|
# Add it up!
# Complete each step below according to the challenge directions and
# include it in this file. Also make sure everything that isn't code
# is commented in the file.
# I worked on this challenge [with: Karen Ball].
# 0. total Pseudocode
# make sure all pseudocode is commented out!
# Input:
# Output:
# Steps to solve the problem.
# define method and create a variable name for the input
# create a variable for the output and assign it a value of 0
# loop through the input array
# for each item, add it to the output variable
# return the output variable
# 1. total initial solution
#def total(n_array)
# sum = 0
# n_array.each do |x|
# sum = sum + x
# end
# return sum
#end
# 3. total refactored solution
def total(n_array)
sum = 0
n_array.each { |x| sum += x }
return sum
end
# 4. sentence_maker pseudocode
# make sure all pseudocode is commented out!
# Input:
# Output:
# Steps to solve the problem.
# define method and create a variable name for the input
# create a variable for the output and assign it an empty string value ('')
# loop through the input array
# also add a space after the item (' ')
# on the output variable, apply a method to capitalize the first letter
# add a period to the output variable
# return the output variable
# 5. sentence_maker initial solution
# def sentence_maker(author)
# novel = ''
# author.each do |a|
# novel = novel + a.to_s + ' '
# end
# novel = novel.capitalize.rstrip + '.'
# return novel
#end
# 6. sentence_maker refactored solution
def sentence_maker(author)
novel = ''
author.each {|a| novel = novel + a.to_s + " " }
novel = novel.capitalize.rstrip + '.'
return novel
end
|
require 'test_helper'
class PetprofilesControllerTest < ActionDispatch::IntegrationTest
setup do
@petprofile = petprofiles(:one)
end
test "should get index" do
get petprofiles_url
assert_response :success
end
test "should get new" do
get new_petprofile_url
assert_response :success
end
test "should create petprofile" do
assert_difference('Petprofile.count') do
post petprofiles_url, params: { petprofile: { DOB: @petprofile.DOB, about: @petprofile.about, available: @petprofile.available, breed: @petprofile.breed, category_id: @petprofile.category_id, gender_id: @petprofile.gender_id, microchipped: @petprofile.microchipped, name: @petprofile.name, pedigree: @petprofile.pedigree, user_id: @petprofile.user_id, vaccinated: @petprofile.vaccinated } }
end
assert_redirected_to petprofile_url(Petprofile.last)
end
test "should show petprofile" do
get petprofile_url(@petprofile)
assert_response :success
end
test "should get edit" do
get edit_petprofile_url(@petprofile)
assert_response :success
end
test "should update petprofile" do
patch petprofile_url(@petprofile), params: { petprofile: { DOB: @petprofile.DOB, about: @petprofile.about, available: @petprofile.available, breed: @petprofile.breed, category_id: @petprofile.category_id, gender_id: @petprofile.gender_id, microchipped: @petprofile.microchipped, name: @petprofile.name, pedigree: @petprofile.pedigree, user_id: @petprofile.user_id, vaccinated: @petprofile.vaccinated } }
assert_redirected_to petprofile_url(@petprofile)
end
test "should destroy petprofile" do
assert_difference('Petprofile.count', -1) do
delete petprofile_url(@petprofile)
end
assert_redirected_to petprofiles_url
end
end
|
# Regular Expression in Ruby
phrase = "The Ruby Programming language is amazing"
# Using the .start_with?
puts phrase.start_with?("The")
puts phrase.downcase.start_with?("the")
puts phrase.start_with?("The Ruby")
puts phrase.start_with?("Ruby")
# Using the end_with?
puts phrase.end_with?("amazing")
puts phrase.downcase.end_with?("amazing")
puts phrase.end_with?("is amazing")
puts phrase.end_with?("language")
# .include?
puts phrase.include?("language")
puts phrase.include?("uby")
puts phrase.include?("RUBY")
puts phrase.upcase.include?("RUBY")
# Basic Regexp
puts //.class
puts phrase =~ /T/
puts phrase =~ /R/
puts phrase =~ /m/
puts /m/ =~ phrase
p phrase =~ /x/
p phrase =~ /Programming/
# .scan method
voicemail = "I can be reached at 555-123-4567 or regexman@gmail.com"
p voicemail.scan(/e/)
p voicemail.scan(/e/).length
p voicemail.scan(/e/).class
p voicemail.scan(/re/)
# more than one character
p voicemail.scan(/[re]/)
p voicemail.scan(/\d/)
p voicemail.scan(/\d+/)
voicemail.scan(/\d+/) {|digit_match| puts digit_match.length}
# The .
puts phrase.scan(/./)
puts phrase.scan(/.ing/)
puts phrase.scan(/a.e/)
|
class Response < ApplicationRecord
belongs_to :prompt, optional: true
belongs_to :user, optional: true
has_many :votes
has_many :voters, through: :votes, :source => :user
end
|
class Api::V1::MakeupBagsController < ApplicationController
before_action :find_makeup_bag, only: [:update, :show, :destroy]
def index
@makeupbags = MakeupBag.all
render json: @makeupbags
end
def show
render json: @makeupbag
end
def create
@makeupbag = MakeupBag.create(makeupbag_params)
if @makeupbag.save
render json: @makeupbag, status: :accepted
else
render json: {errors: @makeupbag.errors.full_messages}, status: :unprocessible_entity
end
end
def update
@makeupbag.update(makeupbag_params)
if @makeupbag.save
render json: @makeupbag, status: :accepted
else
render json: {errors: @makeupbag.errors.full_messages}, status: :unprocessible_entity
end
end
def destroy
@makeupbag.destroy
end
private
def makeupbag_params
params.permit(:name, :description, :user_id)
end
def find_makeup_bag
@makeupbag = MakeupBag.find(params[:id])
end
end
|
require 'test_helper'
class HarvestTest < ActiveSupport::TestCase
def setup
@harvest = Harvest.new(beginning: Date.today, finish: Date.tomorrow)
@harvest.field = Field.new()
end
test "harvest should belong to field" do
assert @harvest.valid?
@harvest.field = nil
assert_not @harvest.valid?
end
test "harvest should have beginning" do
@harvest.beginning = nil
assert_not @harvest.valid?
end
test "harvest should have finish" do
@harvest.finish = ""
assert_not @harvest.valid?
end
test "harvest beginning should be previous to finish" do
@harvest.finish = Date.yesterday
assert_not @harvest.valid?
end
end
|
#
# Copyright 2009 Huygens Instituut for the History of the Netherlands, Den Haag, The Netherlands.
#
# This file is part of New Women Writers.
#
# New Women Writers is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# New Women Writers is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with New Women Writers. If not, see <http://www.gnu.org/licenses/>.
#
class Module
# Returns the classes in the current ObjectSpace where this module has been
# mixed in according to Module#included_modules.
#
# module M
# end
#
# module N
# include M
# end
#
# class C
# include M
# end
#
# class D < C
# end
#
# p M.included_in_classes # => [C, D]
#
def included_in_classes
classes = []
ObjectSpace.each_object(Class) { |k| classes << k if k.included_modules.include?(self) }
classes.reverse.inject([]) do |unique_classes, klass|
unique_classes << klass unless unique_classes.collect { |k| k.to_s }.include?(klass.to_s)
unique_classes
end
end
end |
class Category < ActiveRecord::Base
has_and_belongs_to_many :ads, :join_table => :ads_categories
resourcify
accepts_nested_attributes_for :ads
validates :name, presence: true
end
|
class ChangeImageToFlyerFront < ActiveRecord::Migration
def up
rename_column :events, :image, :flyer_front
end
def down
end
end
|
require 'swagger_helper'
RSpec.describe 'api/v1/incidentfollowups', type: :request do
path "/api/v1/incidentfollowups" do
post "Create an Incidentfollowup" do
tags "Incidentfollowups"
consumes "application/json"
parameter name: :incidentfollowups, in: :body, schema: {
type: :object,
properties: {
incident_id: { type: :integer},
status: { type: :string },
comment: { type: :text },
date: { type: :date_time }
},
required: ['incident_id', 'status', 'comment']
}
response "201", "incidentfollowup created" do
let(:incidentfollowup) { { incident_id: 1, status: 'pending', comment: 'This happened', date: '12/02/2020' } }
run_test!
end
response "422", "invalid request" do
let(:incidentfollowup) { { incident_id: 1 } }
run_test!
end
end
end
path '/incidentfollowups/{id}' do
get 'Retrieves an incidentfollowup' do
tags 'Incidentfollowups'
produces 'application/json', 'application/xml'
parameter name: :id, :in => :path, :type => :string
response '200', 'Incident followups found' do
schema type: :object,
properties: {
id: { type: :integer, },
incident_id: { type: :integer},
date_time: { type: :date_time },
comment: { type: :text },
status: { type: :string },
date: { type: :date_time }
},
required: ['id', 'incident_id', 'status', 'comment']
let(:id) { Incidentfollowups.create(incident_id: 1, status: 'pending', comment: 'This happened', date: '12/02/2020' ).id}
run_test!
end
response '404', 'incidentfollowup not found' do
let(:id) { 'invalid' }
run_test!
end
response '406', 'unsupported accept header' do
let(:'Accept') { 'application/1' }
run_test!
end
end
end
end
|
class Mutations::Profile::Update < GraphQL::Schema::RelayClassicMutation
graphql_name 'updateProfile'
description 'プロフィールの修正'
null true
argument :id, ID, description: 'プロフィールID', required: true
argument :attributes, Types::ProfileAttributes, required: true, description: 'プロフィール属性'
field :profile, Types::UserType, null: true
field :errors, [Types::UserError], null: false
def resolve(id:, attributes:)
current_user = context[:current_user]
raise Errors::Unauthorized if current_user.nil?
profile = User.find(id)
raise Errors::Forbidden if profile != current_user
if profile.update(attributes.to_h)
{ profile: profile, errors: [] }
else
user_errors = profile.errors.map { |attribute, message| { path: ['attributes', attribute], message: message } }
{ profile: nil, errors: user_errors }
end
end
end
|
require "test_helper"
describe User do
describe 'validations' do
it "is invalid without a name" do
user = users(:baduser)
user.valid?.must_equal false
user.errors.messages.must_include :name
end
it "is valid if given a name" do
user = users(:two)
user.valid?
user.errors.messages[:title].must_equal []
end
end
end
|
class CreateActivitiesFriends < ActiveRecord::Migration
def change
create_table :activities_friends, id: false do |t|
t.belongs_to :activity
t.belongs_to :friend
end
end
end
|
class ApplicationController < ActionController::Base
# Prevent CSRF attacks by raising an exception.
# For APIs, you may want to use :null_session instead.
protect_from_forgery with: :exception
protect_from_forgery with: :null_session, if: Proc.new { |c| c.request.format == 'application/json' }
acts_as_token_authentication_handler_for User
# def authenticate_user!
# unless current_user
# return render json: { error: "You are not Authorized!", status: 401 }
# end
# authenticate_user_from_token!
# end
# def authenticate_user_from_token!
# request.headers["X-User-Token"].present? && request.headers["X-User-Email"].present?
# end
end
|
class Board
attr_accessor :cups
def initialize(name1, name2)
@player_1_name = name1
@player_2_name = name2
# Instantiate the cups and fills non-store cups with four stones each
@cups = Array.new(14) { Array.new }
self.place_stones
end
def place_stones
(0..5).each do |idx|
4.times { @cups[idx] << :stone }
end
(7..12).each do |idx|
4.times { @cups[idx] << :stone }
end
end
def valid_move?(start_pos)
raise "Invalid starting cup" if start_pos >= 14
raise "Starting cup is empty" if self.cups[start_pos].empty?
end
def make_move(start_pos, current_player_name)
# Keep track of the number of stones and then empties the cup
num_stones = self.cups[start_pos].length
self.cups[start_pos].clear
counter = 1
# Place the stones into the cups while there are still stones
while counter <= num_stones
new_cup_pos = (start_pos + counter) % 13
if (new_cup_pos == 6) && (current_player_name == @player_1_name)
self.cups[new_cup_pos] << :stone
elsif (new_cup_pos == 13) && (current_player_name == @player_2_name)
self.cups[new_cup_pos] << :stone
else
self.cups[new_cup_pos] << :stone
end
counter += 1
end
# Render the board on each turn
self.render
# Takes care of the logic for the next turn
ending_cup_idx = (start_pos + num_stones) % 14
self.next_turn(current_player_name, ending_cup_idx)
end
def next_turn(current_player_name, ending_cup_idx)
# Helper method to determine whether #make_move returns :switch, :prompt, or ending_cup_idx
if (ending_cup_idx == 6) && (current_player_name == @player_1_name)
:prompt
elsif (ending_cup_idx == 13) && (current_player_name == @player_2_name)
:prompt
elsif self.cups[ending_cup_idx].length == 1
:switch
else
ending_cup_idx
end
end
def render
print " #{@cups[7..12].reverse.map { |cup| cup.count }} \n"
puts "#{@cups[13].count} -------------------------- #{@cups[6].count}"
print " #{@cups.take(6).map { |cup| cup.count }} \n"
puts ""
puts ""
end
def one_side_empty?
player_1_empty = self.cups[0..5].all? { |cup| cup.empty? }
player_2_empty = self.cups[7..12].all? { |cup| cup.empty? }
player_1_empty || player_2_empty
end
def winner
if self.cups[6] == self.cups[13]
return :draw
else
self.cups[6].length > self.cups[13].length ? @player_1_name : @player_2_name
end
end
end
|
require 'rails_helper'
RSpec.describe ResumeParagraph, type: :model do
it {should belong_to(:profile_resume)}
it {should validate_presence_of(:sequence)}
it {should validate_presence_of(:profile_resume)}
end
|
require 'spec_helper'
describe WeWorkRemotely do
class FixtureFetch
def initialize(url)
end
def doc
Nokogiri.parse File.open(File.join(Rails.root, 'spec', 'support', 'fixtures', 'we_work_remotely.html'), 'r').read
end
end
describe '#to_h' do
it 'extracts relevant fields' do
hash = described_class.new('https://weworkremotely.com/jobs/1171', fetcher_class: FixtureFetch).to_h
expect(hash[:title]).to eq("Ruby Developer")
expect(hash[:company_name]).to eq("Stack Builders")
expect(hash[:company_url]).to eq("www.stackbuilders.com")
expect(hash[:description]).to start_with("**About Us**\n")
expect(hash[:how_to_apply]).to start_with("Send a resume to careers@stackbuilders.com")
end
end
end
|
require 'spec_helper'
describe Rack::Handler::Trinidad do
it "registers the trinidad handler" do
Rack::Handler.get(:trinidad).should == described_class
end
it "turns the threads option into jruby min/max runtimes" do
opts = described_class.parse_options({:threads => '2:3'})
opts[:jruby_min_runtimes].should == 2
opts[:jruby_max_runtimes].should == 3
end
it "uses localhost:3000 as default host:port" do
opts = described_class.parse_options
opts[:address].should == 'localhost'
opts[:port].should == 3000
end
it "accepts host:port or address:port as options" do
opts = described_class.parse_options({:host => 'foo', :port => 4000})
opts[:address].should == 'foo'
opts[:port].should == 4000
opts = described_class.parse_options({:address => 'bar', :port => 5000})
opts[:address].should == 'bar'
opts[:port].should == 5000
end
it "creates a servlet for the app" do
servlet = described_class.create_servlet(nil)
servlet.context.server_info.should == 'Trinidad'
servlet.dispatcher.should_not be_nil
end
end
|
# frozen_string_literal: true
class WorkPresenter
include Hydra::Presenter
def self.model_terms
[
:artist,
:creator_display,
:credit_line,
:date_display,
:department,
:dimensions_display,
:earliest_year,
:exhibition_history,
:gallery_location,
:inscriptions,
:latest_year,
:main_ref_number,
:medium_display,
:object_type,
:place_of_origin,
:provenance_text,
:publication_history,
:publ_ver_level
]
end
self.model_class = Work
self.terms = model_terms + CitiResourceTerms.all
def summary_terms
[:uid, :main_ref_number, :created_by, :resource_created, :resource_updated]
end
end
|
class Solution < ActiveRecord::Base
mount_uploader :sol_img, ImageUploader
has_many :line_solutions_items, dependent: :destroy
validates :price, numericality: {greater_than_or_equal_to: 0.01}
end
|
# question 3
def tricky_method(a_string_param, an_array_param)
a_string_param += "rutabaga"
an_array_param << "rutabaga"
end
my_string = "pumpkins"
my_array = ["pumpkins"]
tricky_method(my_string, my_array)
puts "My string looks like this now: #{my_string}"
puts "My array looks like this now: #{my_array}"
# The string will not be mutated by the method, because the reference of my_string
# is passed to the method, and the reassignment (+=) will not mutate the actual object
# that my_string refers to.
# The array will be mutated, since the shovel operator is a mutating operator.
# question 4
def tricky_method_two(a_string_param, an_array_param)
a_string_param << 'rutabaga'
an_array_param = ['pumpkins', 'rutabaga']
end
my_string = "pumpkins"
my_array = ["pumpkins"]
tricky_method_two(my_string, my_array)
puts "My string looks like this now: #{my_string}"
puts "My array looks like this now: #{my_array}"
# My_string will be modified after the method call, since '<<' is a destructive operation
# and works on the value that both my_string and a_string_param are pointing at.
# my_array will not be modified after the method call, since '=' indicates reassignment,
# which will create a new object that an_array_param will be pointing at. my_array will
# still be pointing at the value it had before the method call.
# question 5
def color_valid(color)
color == "blue" || color == "green"
end
p color_valid("blue")
p color_valid("red") |
class MaterialsController < ApplicationController
def create
@m_c = MaterialCategory.find params[:material_category_id]
@material = @m_c.materials.build(material_params)
authorize(@material)
if @material.save
redirect_to course_material_category_path(@m_c.course, @m_c),
notice: "Stworzono"
else
redirect_to course_material_category_path(@m_c.course, @m_c),
error: "Błąd"
end
end
def destroy
@material = Material.find params[:id]
@m_c = @material.material_category
authorize(@material)
if @material.destroy
redirect_to course_material_category_path(@m_c.course, @m_c),
notice: "Usunięto"
else
redirect_to course_material_category_path(@m_c.course, @m_c),
error: "Błąd"
end
end
private
def material_params
params.require(:material).permit(:name, :file)
end
end
|
class DataSourcesRemoveMetadata < ActiveRecord::Migration
def self.up
remove_column :data_sources, :metadata_url
remove_column :data_zip_compressed
end
def self.down
add_column :data_sources, :metadata_url, :string
add_column :data_sources, :data_zip_compressed, :boolean
end
end
|
module ApplicationHelper
def menu_item name, path
klass = current_page?(path) ? " class='active'" : ""
"<li#{klass}><a href='#{path}'>#{name}</a></li>".html_safe
end
def valid_doc_page? page
["classify", "introduction", "classification", "category", "sample", "clients"].include? page
end
def index_li_item name, path
menu_item name, path + "/" + name
end
def selected_option classifier
"selected" if params[:id].present? && params[:id] == classifier.id.to_s
end
end
|
require_relative('./node')
# Creates and manages a binary tree
# node: linked value with/out children
# leaf: last node in a branch
class Tree
attr_accessor :root
def initialize(inputs)
@inputs = inputs.sort.uniq
@root = build_tree(@inputs)
end
# build_tree: forms a network of linked nodes
def build_tree(inputs)
return nil if inputs.empty?
# Divide and conquer algorithm
mid = inputs.size / 2
# Everything between +1 mid and the last value
node = Node.new(inputs[mid])
node.left = build_tree(inputs[0...mid])
node.right = build_tree(inputs[(mid + 1)..inputs.size]) # Does not include duplicate value mid
node
end
# insert: appends value to as a leaf
def insert(value, node = root)
return nil if value == node.data
if value > node.data
node.right.nil? ? node.right = Node.new(value) : insert(value, node.right)
else # value < node.data
node.left.nil? ? node.left = Node.new(value) : insert(value, node.left)
end
end
# delete: removes a selected value and reconnects the children, if exists
def delete(value, node = find(value))
return nil if node.nil?
parent = parent_node(value)
if node.left.nil? && node.right.nil? # no children
delete_leaf(value, parent)
elsif node.left.nil? || node.right.nil? # one child; either left or right
delete_single_child(value, parent, node)
else # two children ; both left and right
delete_double_child(value, parent, node)
end
end
# find: locates a node that contains the datavalue, if available
def find(value, node = root)
return node if value == node.data
if value > node.data
node.right.nil? ? node.left : find(value, node.right)
else
node.left.nil? ? node.left : find(value, node.left)
end
end
# level_order: goes through and returns datavalues in breadth-order
def level_order(node = root, queue = [])
node.data
queue << node.left unless node.left.nil?
queue << node.right unless node.right.nil?
return if queue.empty?
level_order(queue.shift, queue)
# queue.shift removes a value and moves the array over by one
end
# inorder: prints smallest to largest
def inorder(node = root, _array = [])
return if node.nil?
inorder(node.left)
puts node.data
inorder(node.right)
end
def inorder_array(node = root, array = [])
return if node.nil?
inorder_array(node.left, array)
array << node.data
inorder_array(node.right, array)
array
end
# preorder: prints from root to smallest to largest
def preorder(node = root)
return if node.nil?
puts node.data
inorder(node.left)
inorder(node.right)
end
# postorder: prints largest to smallest
def postorder(node = root)
return if node.nil?
inorder(node.left)
inorder(node.right)
puts node.data
end
# height: returns the number of edges from a node to the nearest leaf
def height(node = root)
return -1 if node.nil?
[height(node.left), height(node.right)].max + 1
end
# depth: returns the number of edges from root to the nearest leaf node
def depth(value, node = root)
return 0 if node.data == value # root node is 0 edges
levels = 1 # Including root edge
until node.nil?
node = node.left if node.data > value
node = node.right if node.data < value
levels += 1
return levels if node.data == value
end
end
# balanced: checks if the depth of any side of a node no more than 1 edge
def balanced?(node = root)
height(node.left) == height(node.right) ||
height(node.left) == height(node.right) + 1 ||
height(node.left) == height(node.right) - 1
end
# rebalance: after some changes, a tree can be rebuilt
def rebalance
array = inorder_array
@root = build_tree(array)
end
def pretty_print(node = @root, prefix = '', is_left = true)
pretty_print(node.right, "#{prefix}#{is_left ? '│ ' : ' '}", false) if node.right
puts "#{prefix}#{is_left ? '└── ' : '┌── '}#{node.data}"
pretty_print(node.left, "#{prefix}#{is_left ? ' ' : '│ '}", true) if node.left
end
private
# parent_node: returns the immediate parent of any given node
def parent_node(value, node = root)
return nil if root.data == value
return node if node.left.data == value || node.right.data == value
node.data > value ? parent_node(value, node.left) : parent_node(value, node.right)
end
# delete_leaf:
def delete_leaf(value, parent)
parent.left.data == value ? parent.left = nil : parent.right = nil
end
# delete_single_child:
def delete_single_child(value, parent, node)
case parent.left.data == value
when true # Is Left
parent.left = (node.left.nil? ? node.right : node.left)
when false # Is Right
parent.right = (node.left.nil? ? node.right : node.left)
end
end
# delete_double_child:
def delete_double_child(_value, parent, node)
leafmost = leafmost_left(node.right)
delete(leafmost.data) # Prevent backlinks
case parent.left == node
when true
leafmost.left = node.left
leafmost.right = node.right
parent.left = leafmost
when false
leafmost.left = node.left
leafmost.right = node.right
parent.right = leafmost
end
end
# swap_nodes:
def swap_nodes(one, two, parent, direction)
two.left = one.left
two.right = one.right
parent.right = two if direction == 'right'
parent.left = two if direction == 'left'
end
# leafmost_left:
def leafmost_left(node)
return node if node.left.nil?
node = node.left
leafmost_left(node)
end
end
|
# encoding: utf-8
# This file should contain all the record creation needed to seed the database with its default values.
# The data can then be loaded with the rake db:seed (or created alongside the db with db:setup).
#
# Examples:
#
# cities = City.create([{ :name => 'Chicago' }, { :name => 'Copenhagen' }])
# Mayor.create(:name => 'Daley', :city => cities.first)
fields = ["Arquitetura",
"Ciência da Computação",
"Direito",
"Engenharia Civil",
"Educação Física"]
fields.each do |t|
Field.create(:description => t)
end
Internship.create(:title=>"Escritório de Silvio Bararó",
:description=>"Maecenas sed diam eget risus varius blandit sit amet non magna. Vivamus sagittis lacus vel augue laoreet rutrum faucibus dolor auctor. Cras mattis consectetur purus sit amet fermentum. Nulla vitae elit libero, a pharetra augue.")
Internship.create(:title=>"Design Gráfico I3E",
:description=>"Nullam quis risus eget urna mollis ornare vel eu leo. Vivamus sagittis lacus vel augue laoreet rutrum faucibus dolor auctor. Cras mattis consectetur purus sit amet fermentum.")
Internship.create(:title=>"Escritório de Marcelo Sá",
:description=>"Sed posuere consectetur est at lobortis. Maecenas faucibus mollis interdum. Duis mollis, est non commodo luctus, nisi erat porttitor ligula, eget lacinia odio sem nec elit. Donec ullamcorper nulla non metus auctor fringilla.")
Internship.create(:title=>"Escritório de Advocacia Moedo Barbosa",
:description=>"Cras mattis consectetur purus sit amet fermentum. Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Etiam porta sem malesuada magna mollis euismod. Donec sed odio dui. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec ullamcorper nulla non metus auctor fringilla.")
Internship.create(:title=>"Desenvolvedor Java",
:description=>"Donec ullamcorper nulla non metus auctor fringilla. Cras mattis consectetur purus sit amet fermentum. Vestibulum id ligula porta felis euismod semper. Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Sed posuere consectetur est at lobortis.")
|
class AddAttachmentLogToLog < ActiveRecord::Migration
def self.up
add_column :logs, :log_file_name, :string
add_column :logs, :log_content_type, :string
add_column :logs, :log_file_size, :integer
add_column :logs, :log_updated_at, :datetime
end
def self.down
remove_column :logs, :log_file_name
remove_column :logs, :log_content_type
remove_column :logs, :log_file_size
remove_column :logs, :log_updated_at
end
end
|
# More string methods on Ruby
name = "Charles Babbage"
p name.include?("s")
p name.include?("z")
puts
p "".empty?
p "Arithmometer".empty?
puts
inventor = "Herman Hollerith"
last_name = inventor[7, 9]
p last_name.nil?
|
class Api::V1::FormsController < ApplicationController
before_action :authenticate_with_token!, only: [:create]
respond_to :json
def index
respond_with Form.all
end
def show
respond_with Form.find(params[:id])
end
def create
form = current_user.forms.build(form_params)
if form.save
render json: form, status: 201, location: [:api, form]
else
render json: { errors: form.errors }, status: 422
end
end
def update
form = current_user.form.find(params[:id])
if form.update(form_params)
render json: form, status: 200, location: [:api, form]
else
render json: { errors: form.errors }, status: 422
end
end
private
def form_params
params.require(:form).permit(:name, :body, :submitted)
end
end
|
class RenameColumnType < ActiveRecord::Migration
def change
rename_column :planets, :type, :planet_type
end
end
|
require 'forwardable'
require 'vanagon/extensions/string'
require 'vanagon/logger'
class Vanagon
# Environment is a validating wrapper around a delegated Hash,
# analogous to Ruby's built in accessor Env. It's intended to be
# used for defining multiple Environments, which can be used and
# manipulated the same way a bare Hash would be. We're delegating
# instead of subclassing because subclassing from Ruby Core is
# inviting calamity -- that stuff is written in C and may not
# correspond to assumptions you could safely make about Ruby.
class Environment
extend Forwardable
# @!method []
# @see Hash#[]
# @!method keys
# @see Hash#keys
# @!method values
# @see Hash#values
# @!method empty?
# @see Hash#empty?
def_delegators :@data, :[], :keys, :values, :empty?
# @!method each
# @see Hash#each
# @!method each_pair
# @see Hash#each_pair
def_delegators :@data, :each, :each_pair, :each_key, :each_value
def_delegators :@data, :each_with_index, :each_with_object
def_delegators :@data, :map, :flat_map
# @!method delete
# @see Hash#delete
# @!method delete_if
# @see Hash#delete_if
def_delegators :@data, :delete, :delete_if
# @!method to_h
# @see Hash#to_h
# @!method to_hash
# @see Hash#to_h
def_delegators :@data, :to_h, :to_hash
# Create a new Environment
# @return [Vanagon::Environment] a new Environment, with no defined env. vars.
def initialize
@data = {}
end
# Associates the value given by value with the key given by key. Keys will
# be cast to Strings, and should conform to the Open Group's guidelines for
# portable shell variable names:
#
# Environment variable names used by the utilities in the Shell and
# Utilities volume of IEEE Std 1003.1-2001 consist solely of uppercase
# letters, digits, and the '_' (underscore) from the characters defined
# in Portable Character Set and do not begin with a digit.
#
# Values will be cast to Strings, and will be stored precisely as given,
# so any escaped characters, single or double quotes, or whitespace will be
# preserved exactly as passed during assignment.
#
# @param key [String]
# @param value [String, Integer]
# @raise [ArgumentError] if key or value cannot be cast to a String
def []=(key, value)
@data.update({ validate_key(key) => validate_value(value) })
end
# Returns a new Environment containing the contents of other_env and the
# contents of env.
# @param other_env [Environment]
# @example Merge two Environments
# >> local = Vanagon::Environment.new
# => #<Vanagon::Environment:0x007fc54d913f38 @data={}>
# >> global = Vanagon::Environment.new
# => #<Vanagon::Environment:0x007fc54b06da70 @data={}>
# >> local['PATH'] = '/usr/local/bin:/usr/bin:/bin'
# >> global['CC'] = 'ccache gcc'
# >> local.merge global
# => #<Vanagon::Environment:0x007fc54b0a72e8 @data={"PATH"=>"/usr/local/bin:/usr/bin:/bin", "CC"=>"ccache gcc"}>
def merge(other_env)
env_copy = self.dup
other_env.each_pair do |k, v|
env_copy[k] = v
end
env_copy
end
alias update merge
# Adds the contents of other_env to env.
# @param other_env [Environment]
# @example Merge two Environments
# >> local = Vanagon::Environment.new
# => #<Vanagon::Environment:0x007f8c68933b08 @data={}>
# >> global = Vanagon::Environment.new
# => #<Vanagon::Environment:0x007f8c644e5640 @data={}>
# >> local['PATH'] = '/usr/local/bin:/usr/bin:/bin'
# >> global['CC'] = 'ccache gcc'
# >> local.merge! global
# => #<Vanagon::Environment:0x007f8c68933b08 @data={"PATH"=>"/usr/local/bin:/usr/bin:/bin", "CC"=>"ccache gcc"}>
def merge!(other_env)
@data = merge(other_env).instance_variable_get(:@data)
end
# Converts env to an array of "#{key}=#{value}" strings, suitable for
# joining into a command.
# @example Convert to an Array
# >> local = Vanagon::Environment.new
# => #<Vanagon::Environment:0x007f8c68991258 @data={}>
# >> local['PATH'] = '/usr/local/bin:/usr/bin:/bin'
# => "/usr/local/bin:/usr/bin:/bin"
# >> local['CC'] = 'clang'
# => "clang"
# >> local.to_a
# => ["PATH=\"/usr/local/bin:/usr/bin:/bin\"", "CC=\"clang\""]
def to_a(delim = "=")
@data.map { |k, v| %(#{k}#{delim}#{v}) }
end
alias to_array to_a
# Converts env to a string by concatenating together all key-value pairs
# with a single space.
# @example Convert to an Array
# >> local = Vanagon::Environment.new
# => #<Vanagon::Environment:0x007f8c68014358 @data={}>
# >> local['PATH'] = '/usr/local/bin:/usr/bin:/bin'
# >> local['CC'] = 'clang'
# >> puts local
# PATH=/usr/local/bin:/usr/bin:/bin
# >>
def to_s
to_a.join("\s")
end
alias to_string to_s
def sanitize_subshells(str)
pattern = %r{\$\$\((.*?)\)}
escaped_variables = str.scan(pattern).flatten
return str if escaped_variables.empty?
warning = [%(Value "#{str}" looks like it's escaping one or more values for subshell interpolation.)]
escaped_variables.each { |v| warning.push %(\t"$$(#{v})" will be coerced to "$(shell #{v})") }
warning.push <<-WARNING.undent
All environment variables will now be resolved by Make before they're executed
by the shell. These variables will be mangled for you for now, but you should
update your project's parameters.
WARNING
VanagonLogger.info warning.join("\n")
str.gsub(pattern, '$(shell \1)')
end
private :sanitize_subshells
def sanitize_variables(str)
pattern = %r{\$\$([\w]+)}
escaped_variables = str.scan(pattern).flatten
return str if escaped_variables.empty?
warning = [%(Value "#{str}" looks like it's escaping one or more shell variable names for shell interpolation.)]
escaped_variables.each { |v| warning.push %(\t"$$#{v}" will be coerced to "$(#{v})") }
warning.push <<-WARNING.undent
All environment variables will now be resolved by Make before they're executed
by the shell. These variables will be mangled for you for now, but you should
update your project's parameters.
WARNING
VanagonLogger.info warning.join("\n")
str.gsub(pattern, '$(\1)')
end
private :sanitize_variables
# Cast key to a String, and validate that it does not contain invalid
# characters, and that it does not begin with a digit
# @param key [Object]
# @raise [ArgumentError] if key is not a String, if key contains invalid
# characters, or if key begins with a digit
def validate_key(key)
environment_string = key.to_s
if environment_string[0] =~ /\d/
raise ArgumentError, 'environment variable Name cannot begin with a digit'
end
invalid_characters = environment_string
.scan(/[^\w]/)
.uniq
.map { |char| %("#{char}") }
.join(', ')
return environment_string if invalid_characters.empty?
raise ArgumentError,
"environment variable Name contains invalid characters: #{invalid_characters}"
end
private :validate_key
# Cast str to a String, and validate that the value
# of str cannot be split into more than a single String by #shellsplit.
# @param value [Object]
def validate_value(str)
# sanitize the value, which should look for any Shell escaped
# variable names inside of the value.
sanitize_variables(sanitize_subshells(str.to_s))
end
private :validate_value
end
end
|
require_relative 'human_player'
require_relative 'board'
class Game
attr_accessor :num_rows, :num_cols, :player_one, :player_two, :board, :current_player
def initialize(num_rows = 6, num_cols = 7)
@num_rows = num_rows
@num_cols = num_cols
@player_one = HumanPlayer.new("b")
@player_two = HumanPlayer.new("r")
@board = Board.new
@current_player = self.player_one
end
def valid_input?(input)
if !input.match(/\A\d+\Z/)
puts "Invalid Syntax"
return false
else
col = parse(input)
if !(0...num_cols).include?(col)
puts "Column index must be in the range 0 to #{num_cols}"
return false
elsif self.board.is_full?(col)
puts "Column #{col} is full."
return false
end
end
true
end
def get_col
input = nil
until input && valid_input?(input)
prompt
input = gets.chomp
end
parse(input)
end
def prompt
puts "Please enter the column you want to put your #{self.current_player.color} disk"
print "> "
end
def parse(string)
string.to_i
end
def play
play_turn until board.over?
puts "Congratulations, #{board.winner_is} wins!"
end
def play_turn
board.render
col = get_col
drop_disc(col)
switch_player
end
def switch_player
self.current_player = (self.current_player == self.player_one ? self.player_two : self.player_one)
end
def drop_disc(col)
board.drop_disc(col, Disc.new(current_player.color))
end
end
if __FILE__ == $PROGRAM_NAME
Game.new.play
end
|
# frozen_string_literal: true
module Api
module V1
# API routes extend from this controller
class ApiController < ApplicationController
skip_before_action :verify_authenticity_token
before_action :authenticate_user_from_token!
def ping
render json: { message: "pong" }
end
end
end
end
|
class Interest < ApplicationRecord
validates :user_id, uniqueness: { scope: [:post_id] }
belongs_to :post
belongs_to :user
end
|
=begin
Swagger atNuda
This is a sample atNuda server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/).
OpenAPI spec version: 1.0.0
Contact: xe314m@gmail.com
Generated by: https://github.com/swagger-api/swagger-codegen.git
=end
class PortfoliosController < ApplicationController
def create
# Your code here
bad_request
render json: { "date": {"status": 201, "message" => "OK" } } unless error?
end
def destroy
# Your code here
bad_request
not_found
render json: { "date":{ "status": 205, "message" => "OK" } } unless error?
end
def show
# Your code here
data = params.require(:data)
positions = data[:positions]
status = data[:status]
json = {
data: [
{
"portfolio": {
"uuid": "portxxxxx1",
"site_url": "https://www.google.com/",
"image_urls": [
"http://localhost:4200/images/site1.jpeg",
"http://localhost:4200/images/site2.jpeg",
"http://localhost:4200/images/site3.jpeg"
],
},
"explanation": "一言",
"comments": [
{
"myself": true,
"comment": "私のコメント"
},
{
"myself": false,
"comment": "誰かのコメント"
}
],
"corrections": [
{
"myself": true,
"correction": "添削への返信"
},
{
"myself": false,
"correction": "誰かの添削コメント"
},
],
"like": 4,
"user": {
"uuid": "userxxxxx",
"name": "john",
"positions": positions,
"status": status,
"user_small_images_url": "https://www.google.com/",
},
},
{
"portfolio": {
"uuid": "portxxxxx1",
"site_url": "https://www.google.com/",
"image_urls": [
"http://localhost:4200/images/site1.jpeg",
"http://localhost:4200/images/site2.jpeg",
"http://localhost:4200/images/site3.jpeg"
],
},
"explanation": "一言",
"comments": [
{
"myself": true,
"comment": "私のコメント"
},
{
"myself": false,
"comment": "誰かのコメント"
}
],
"corrections": [
{
"myself": true,
"correction": "添削への返信"
},
{
"myself": false,
"correction": "誰かの添削コメント"
},
],
"like": 3,
"user": {
"uuid": "userxxxxx",
"name": "john",
"positions": positions,
"status": status,
"user_small_images_url": "https://www.google.com/",
},
},
{
"portfolio": {
"uuid": "portxxxxx1",
"site_url": "https://www.google.com/",
"image_urls": [
"http://localhost:4200/images/site1.jpeg",
"http://localhost:4200/images/site2.jpeg",
"http://localhost:4200/images/site3.jpeg"
],
},
"explanation": "一言",
"comments": [
{
"myself": true,
"comment": "私のコメント"
},
{
"myself": false,
"comment": "誰かのコメント"
}
],
"corrections": [
{
"myself": true,
"correction": "添削への返信"
},
{
"myself": false,
"correction": "誰かの添削コメント"
},
],
"like": 23,
"user": {
"uuid": "userxxxxx",
"name": "john",
"positions": positions,
"status": status,
"user_small_images_url": "https://www.google.com/",
},
},
{
"portfolio": {
"uuid": "portxxxxx1",
"site_url": "https://www.google.com/",
"image_urls": [
"http://localhost:4200/images/site1.jpeg",
"http://localhost:4200/images/site2.jpeg",
"http://localhost:4200/images/site3.jpeg"
],
},
"explanation": "一言",
"comments": [
{
"myself": true,
"comment": "私のコメント"
},
{
"myself": false,
"comment": "誰かのコメント"
}
],
"corrections": [
{
"myself": true,
"correction": "添削への返信"
},
{
"myself": false,
"correction": "誰かの添削コメント"
},
],
"like": 400,
"user": {
"uuid": "userxxxxx",
"name": "john",
"positions": positions,
"status": status,
"user_small_images_url": "https://www.google.com/",
},
},
{
"portfolio": {
"uuid": "portxxxxx1",
"site_url": "https://www.google.com/",
"image_urls": [
"http://localhost:4200/images/site1.jpeg",
"http://localhost:4200/images/site2.jpeg",
"http://localhost:4200/images/site3.jpeg"
],
},
"explanation": "一言",
"comments": [
{
"myself": true,
"comment": "私のコメント"
},
{
"myself": false,
"comment": "誰かのコメント"
}
],
"corrections": [
{
"myself": true,
"correction": "添削への返信"
},
{
"myself": false,
"correction": "誰かの添削コメント"
},
],
"like": 2,
"user": {
"uuid": "userxxxxx",
"name": "john",
"positions": positions,
"status": status,
"user_small_images_url": "https://www.google.com/",
},
},
{
"portfolio": {
"uuid": "portxxxxx1",
"site_url": "https://www.google.com/",
"image_urls": [
"http://localhost:4200/images/site1.jpeg",
"http://localhost:4200/images/site2.jpeg",
"http://localhost:4200/images/site3.jpeg"
],
},
"explanation": "一言",
"comments": [
{
"myself": true,
"comment": "私のコメント"
},
{
"myself": false,
"comment": "誰かのコメント"
}
],
"corrections": [
{
"myself": true,
"correction": "添削への返信"
},
{
"myself": false,
"correction": "誰かの添削コメント"
},
],
"like": 0,
"user": {
"uuid": "userxxxxx",
"name": "john",
"positions": positions,
"status": status,
"user_small_images_url": "https://www.google.com/",
},
},
]
}
bad_request
not_found
render json: json unless error?
end
def update
# Your code here
bad_request
not_found
render json: { "date": {"status": 200, "message" => "OK" } } unless error?
end
end
|
class OpenAPIParser::SchemaValidator
module MinimumMaximum
# check minimum and maximum value by schema
# @param [Object] value
# @param [OpenAPIParser::Schemas::Schema] schema
def check_minimum_maximum(value, schema)
include_min_max = schema.minimum || schema.maximum
return [value, nil] unless include_min_max
validate(value, schema)
[value, nil]
rescue OpenAPIParser::OpenAPIError => e
return [nil, e]
end
private
def validate(value, schema)
reference = schema.object_reference
if schema.minimum
if schema.exclusiveMinimum && value <= schema.minimum
raise OpenAPIParser::LessThanExclusiveMinimum.new(value, reference)
elsif value < schema.minimum
raise OpenAPIParser::LessThanMinimum.new(value, reference)
end
end
if schema.maximum
if schema.exclusiveMaximum && value >= schema.maximum
raise OpenAPIParser::MoreThanExclusiveMaximum.new(value, reference)
elsif value > schema.maximum
raise OpenAPIParser::MoreThanMaximum.new(value, reference)
end
end
end
end
end
|
class Guide < ActiveRecord::Base
belongs_to :user
has_many :comments, :dependent => :destroy
validates_presence_of :user
validates_presence_of :body
validates_presence_of :name
validates_presence_of :category
validates_uniqueness_of :name
attr_accessible :name, :body, :category, :user, :avatar, :video
ajaxful_rateable :stars => 5, :dimensions => [:rating]
opinio_subjectum
def all_comments
self.comments.collect { |c| [c] + c.comments }.flatten
end
def more_from_category
Guide.find_all_by_category(self.category, :limit => 4, :conditions => ["id != ?", self.id])
end
def self.all_categories
Guide.select(:category).group(:category).collect { |g| g.category }
end
end
|
class ApplicationController < ActionController::Base
# Prevent CSRF attacks by raising an exception.
# For APIs, you may want to use :null_session instead.
protect_from_forgery with: :exception
around_filter :detect_rouge_version
[Highlighter::LexerNotFound,
Highlighter::FormatterNotFound].each do |highlighter_error|
rescue_from highlighter_error do |exception|
@parse = "<span class='err'>Error: #{exception.message}</span>".html_safe
render 'parses/create'
end
end
def detect_rouge_version
version = params[:rouge_version]&.strip
return yield unless version
return yield unless version =~ /\A\d+[.]\d+[.]\d+\z/
return yield unless RougeVersion.version(params[:rouge_version])
RougeVersion.with_version(params[:rouge_version]) { yield }
end
def rouge
RougeVersion.current
end
end
|
class Piece
attr_accessor :pos, :color
def initialize(pos, board, color)
@pos = pos
@board = board
@color = color
end
def present?
true
end
# def to_s
# " x "
# end
# def moves
# moves = []
#
# xy_moves = [[0,-1],[0,1],[1,0],[-1,0]]
# potential_moves = xy_moves.map do |x,y|
# [x + @pos[0], y + @pos[1]]
# end
# potential_moves.each {|move| moves << move if in_bounds?(move)}
# moves
# end
#
# def in_bounds?(pos)
# pos.all? { |x| x.between?(0, 7) }
# end
end
class NullPiece
attr_reader :color
def initialize
@color = nil
end
def present?
false
end
def to_s
" "
end
end
|
# frozen_string_literal: true
require "test_helper"
module Quilt
class HeaderCsrfStrategyTest < Minitest::Test
def test_raises_an_exception_if_the_samesite_header_is_missing
DummyRequest.any_instance.stubs(:headers).returns({})
strategy = HeaderCsrfStrategy.new(DummyController.new)
assert_raises(HeaderCsrfStrategy::NoSameSiteHeaderError) do
strategy.handle_unverified_request
end
end
def test_raises_an_exception_if_the_samesite_header_has_an_unexpected_value
headers = {}
headers[HeaderCsrfStrategy::HEADER] = "hi hello this is not the value you are looking for"
DummyRequest.any_instance.stubs(:headers).returns(headers)
strategy = HeaderCsrfStrategy.new(DummyController.new)
assert_raises(HeaderCsrfStrategy::NoSameSiteHeaderError) do
strategy.handle_unverified_request
end
end
def test_noops_if_the_samesite_header_is_present
headers = {}
headers[HeaderCsrfStrategy::HEADER] = HeaderCsrfStrategy::HEADER_VALUE
DummyRequest.any_instance.stubs(:headers).returns(headers)
strategy = HeaderCsrfStrategy.new(DummyController.new)
strategy.handle_unverified_request
end
end
end
class DummyController
def request
DummyRequest.new
end
end
class DummyRequest
end
|
module DataMapper
module Associations
# Base class for relationships. Each type of relationship
# (1 to 1, 1 to n, n to m) implements a subclass of this class
# with methods like get and set overridden.
class Relationship
include Extlib::Assertions
OPTIONS = [ :child_repository_name, :parent_repository_name, :child_key, :parent_key, :min, :max, :inverse, :reader_visibility, :writer_visibility ].to_set
# Relationship name
#
# @example for :parent association in
#
# class VersionControl::Commit
# # ...
#
# belongs_to :parent
# end
#
# name is :parent
#
# @api semipublic
attr_reader :name
# Options used to set up association of this relationship
#
# @example for :author association in
#
# class VersionControl::Commit
# # ...
#
# belongs_to :author, :model => 'Person'
# end
#
# options is a hash with a single key, :model
#
# @api semipublic
attr_reader :options
# ivar used to store collection of child options in source
#
# @example for :commits association in
#
# class VersionControl::Branch
# # ...
#
# has n, :commits
# end
#
# instance variable name for source will be @commits
#
# @api semipublic
attr_reader :instance_variable_name
# Repository from where child objects are loaded
#
# @api semipublic
attr_reader :child_repository_name
# Repository from where parent objects are loaded
#
# @api semipublic
attr_reader :parent_repository_name
# Minimum number of child objects for relationship
#
# @example for :cores association in
#
# class CPU::Multicore
# # ...
#
# has 2..n, :cores
# end
#
# minimum is 2
#
# @api semipublic
attr_reader :min
# Maximum number of child objects for
# relationship
#
# @example for :fouls association in
#
# class Basketball::Player
# # ...
#
# has 0..5, :fouls
# end
#
# maximum is 5
#
# @api semipublic
attr_reader :max
# Returns the visibility for the source accessor
#
# @return [Symbol]
# the visibility for the accessor added to the source
#
# @api semipublic
attr_reader :reader_visibility
# Returns the visibility for the source mutator
#
# @return [Symbol]
# the visibility for the mutator added to the source
#
# @api semipublic
attr_reader :writer_visibility
# Returns query options for relationship.
#
# For this base class, always returns query options
# has been initialized with.
# Overriden in subclasses.
#
# @api private
attr_reader :query
# Returns a hash of conditions that scopes query that fetches
# target object
#
# @return [Hash]
# Hash of conditions that scopes query
#
# @api private
def source_scope(source)
{ inverse => source }
end
# Creates and returns Query instance that fetches
# target resource(s) (ex.: articles) for given target resource (ex.: author)
#
# @api semipublic
def query_for(source, other_query = nil)
repository_name = relative_target_repository_name_for(source)
DataMapper.repository(repository_name).scope do
query = target_model.query.dup
query.update(self.query)
query.update(source_scope(source))
query.update(other_query) if other_query
query.update(:fields => query.fields | target_key)
end
end
# Returns model class used by child side of the relationship
#
# @return [Resource]
# Model for association child
#
# @api private
def child_model
@child_model ||= (@parent_model || Object).find_const(child_model_name)
rescue NameError
raise NameError, "Cannot find the child_model #{child_model_name} for #{parent_model_name} in #{name}"
end
# TODO: document
# @api private
def child_model?
child_model
true
rescue NameError
false
end
# TODO: document
# @api private
def child_model_name
@child_model ? child_model.name : @child_model_name
end
# Returns a set of keys that identify the target model
#
# @return [PropertySet]
# a set of properties that identify the target model
#
# @api semipublic
def child_key
return @child_key if defined?(@child_key)
repository_name = child_repository_name || parent_repository_name
properties = child_model.properties(repository_name)
@child_key = if @child_properties
child_key = properties.values_at(*@child_properties)
properties.class.new(child_key).freeze
else
properties.key
end
end
# Access Relationship#child_key directly
#
# @api private
alias relationship_child_key child_key
private :relationship_child_key
# Returns model class used by parent side of the relationship
#
# @return [Resource]
# Class of association parent
#
# @api private
def parent_model
@parent_model ||= (@child_model || Object).find_const(parent_model_name)
rescue NameError
raise NameError, "Cannot find the parent_model #{parent_model_name} for #{child_model_name} in #{name}"
end
# TODO: document
# @api private
def parent_model?
parent_model
true
rescue NameError
false
end
# TODO: document
# @api private
def parent_model_name
@parent_model ? parent_model.name : @parent_model_name
end
# Returns a set of keys that identify parent model
#
# @return [PropertySet]
# a set of properties that identify parent model
#
# @api private
def parent_key
return @parent_key if defined?(@parent_key)
repository_name = parent_repository_name || child_repository_name
properties = parent_model.properties(repository_name)
@parent_key = if @parent_properties
parent_key = properties.values_at(*@parent_properties)
properties.class.new(parent_key).freeze
else
properties.key
end
end
# Loads and returns "other end" of the association.
# Must be implemented in subclasses.
#
# @api semipublic
def get(resource, other_query = nil)
raise NotImplementedError, "#{self.class}#get not implemented"
end
# Gets "other end" of the association directly
# as @ivar on given resource. Subclasses usually
# use implementation of this class.
#
# @api semipublic
def get!(resource)
resource.instance_variable_get(instance_variable_name)
end
# Sets value of the "other end" of association
# on given resource. Must be implemented in subclasses.
#
# @api semipublic
def set(resource, association)
raise NotImplementedError, "#{self.class}#set not implemented"
end
# Sets "other end" of the association directly
# as @ivar on given resource. Subclasses usually
# use implementation of this class.
#
# @api semipublic
def set!(resource, association)
resource.instance_variable_set(instance_variable_name, association)
end
# Eager load the collection using the source as a base
#
# @param [Resource, Collection] source
# the source to query with
# @param [Query, Hash] query
# optional query to restrict the collection
#
# @return [Collection]
# the loaded collection for the source
#
# @api private
def eager_load(source, query = nil)
target_maps = Hash.new { |h,k| h[k] = [] }
collection_query = query_for(source, query)
# TODO: create an object that wraps this logic, and when the first
# kicker is fired, then it'll load up the collection, and then
# populate all the other methods
collection = source.model.all(collection_query).each do |target|
target_maps[target_key.get(target)] << target
end
Array(source).each do |source|
key = target_key.typecast(source_key.get(source))
eager_load_targets(source, target_maps[key], query)
end
collection
end
# Checks if "other end" of association is loaded on given
# resource.
#
# @api semipublic
def loaded?(resource)
assert_kind_of 'resource', resource, source_model
resource.instance_variable_defined?(instance_variable_name)
end
# Test the source to see if it is a valid target
#
# @param [Object] source
# the resource or collection to be tested
#
# @return [Boolean]
# true if the resource is valid
#
# @api semipulic
def valid?(source)
return true if source.nil?
case source
when Array, Collection then valid_collection?(source)
when Resource then valid_resource?(source)
else
raise ArgumentError, "+source+ should be an Array or Resource, but was a #{source.class.name}"
end
end
# Compares another Relationship for equality
#
# @param [Relationship] other
# the other Relationship to compare with
#
# @return [Boolean]
# true if they are equal, false if not
#
# @api public
def eql?(other)
return true if equal?(other)
instance_of?(other.class) && cmp?(other, :eql?)
end
# Compares another Relationship for equivalency
#
# @param [Relationship] other
# the other Relationship to compare with
#
# @return [Boolean]
# true if they are equal, false if not
#
# @api public
def ==(other)
return true if equal?(other)
return false if kind_of_inverse?(other)
other.respond_to?(:cmp_repository?, true) &&
other.respond_to?(:cmp_model?, true) &&
other.respond_to?(:cmp_key?, true) &&
other.respond_to?(:query) &&
cmp?(other, :==)
end
# Get the inverse relationship from the target model
#
# @api semipublic
def inverse
return @inverse if defined?(@inverse)
if kind_of_inverse?(options[:inverse])
return @inverse = options[:inverse]
end
relationships = target_model.relationships(relative_target_repository_name).values
@inverse = relationships.detect { |relationship| inverse?(relationship) } ||
invert
@inverse.child_key
@inverse
end
# TODO: document
# @api private
def relative_target_repository_name
target_repository_name || source_repository_name
end
# TODO: document
# @api private
def relative_target_repository_name_for(source)
target_repository_name || if source.respond_to?(:repository)
source.repository.name
else
source_repository_name
end
end
private
# TODO: document
# @api private
attr_reader :child_properties
# TODO: document
# @api private
attr_reader :parent_properties
# Initializes new Relationship: sets attributes of relationship
# from options as well as conventions: for instance, @ivar name
# for association is constructed by prefixing @ to association name.
#
# Once attributes are set, reader and writer are created for
# the resource association belongs to
#
# @api semipublic
def initialize(name, child_model, parent_model, options = {})
initialize_object_ivar('child_model', child_model)
initialize_object_ivar('parent_model', parent_model)
@name = name
@instance_variable_name = "@#{@name}".freeze
@options = options.dup.freeze
@child_repository_name = @options[:child_repository_name]
@parent_repository_name = @options[:parent_repository_name]
@child_properties = @options[:child_key].try_dup.freeze
@parent_properties = @options[:parent_key].try_dup.freeze
@min = @options[:min]
@max = @options[:max]
@reader_visibility = @options.fetch(:reader_visibility, :public)
@writer_visibility = @options.fetch(:writer_visibility, :public)
# TODO: normalize the @query to become :conditions => AndOperation
# - Property/Relationship/Path should be left alone
# - Symbol/String keys should become a Property, scoped to the target_repository and target_model
# - Extract subject (target) from Operator
# - subject should be processed same as above
# - each subject should be transformed into AbstractComparison
# object with the subject, operator and value
# - transform into an AndOperation object, and return the
# query as :condition => and_object from self.query
# - this should provide the best performance
@query = @options.except(*self.class::OPTIONS).freeze
create_reader
create_writer
end
# Set the correct ivars for the named object
#
# This method should set the object in an ivar with the same name
# provided, plus it should set a String form of the object in
# a second ivar.
#
# @param [String]
# the name of the ivar to set
# @param [#name, #to_str, #to_sym] object
# the object to set in the ivar
#
# @return [String]
# the String value
#
# @raise [ArgumentError]
# raise when object does not respond to expected methods
#
# @api private
def initialize_object_ivar(name, object)
if object.respond_to?(:name)
instance_variable_set("@#{name}", object)
initialize_object_ivar(name, object.name)
elsif object.respond_to?(:to_str)
instance_variable_set("@#{name}_name", object.to_str.dup.freeze)
elsif object.respond_to?(:to_sym)
instance_variable_set("@#{name}_name", object.to_sym)
else
raise ArgumentError, "#{name} does not respond to #to_str or #name"
end
object
end
# Dynamically defines reader method for source side of association
# (for instance, method article for model Paragraph)
#
# @api semipublic
def create_reader
reader_name = name.to_s
return if source_model.resource_method_defined?(reader_name)
source_model.class_eval <<-RUBY, __FILE__, __LINE__ + 1
#{reader_visibility} # public
def #{reader_name}(query = nil) # def author(query = nil)
relationships[#{name.inspect}].get(self, query) # relationships[:author].get(self, query)
end # end
RUBY
end
# Dynamically defines writer method for source side of association
# (for instance, method article= for model Paragraph)
#
# @api semipublic
def create_writer
writer_name = "#{name}="
return if source_model.resource_method_defined?(writer_name)
source_model.class_eval <<-RUBY, __FILE__, __LINE__ + 1
#{writer_visibility} # public
def #{writer_name}(target) # def author=(target)
relationships[#{name.inspect}].set(self, target) # relationships[:author].set(self, target)
end # end
RUBY
end
# Sets the association targets in the resource
#
# @param [Resource] source
# the source to set
# @param [Array<Resource>] targets
# the targets for the association
# @param [Query, Hash] query
# the query to scope the association with
#
# @return [undefined]
#
# @api private
def eager_load_targets(source, targets, query)
raise NotImplementedError, "#{self.class}#eager_load_targets not implemented"
end
# TODO: document
# @api private
def valid_collection?(collection)
if collection.instance_of?(Array) || collection.loaded?
collection.all? { |resource| valid_resource?(resource) }
else
collection.model <= target_model && (collection.query.fields & target_key) == target_key
end
end
# TODO: document
# @api private
def valid_resource?(resource)
resource.kind_of?(target_model) &&
target_key.zip(target_key.get!(resource)).all? { |property, value| property.valid?(value) }
end
# TODO: document
# @api private
def inverse?(other)
return true if @inverse.equal?(other)
other != self &&
kind_of_inverse?(other) &&
cmp_repository?(other, :==, :child) &&
cmp_repository?(other, :==, :parent) &&
cmp_model?(other, :==, :child) &&
cmp_model?(other, :==, :parent) &&
cmp_key?(other, :==, :child) &&
cmp_key?(other, :==, :parent)
# TODO: match only when the Query is empty, or is the same as the
# default scope for the target model
end
# TODO: document
# @api private
def inverse_name
if options[:inverse].kind_of?(Relationship)
options[:inverse].name
else
options[:inverse]
end
end
# TODO: document
# @api private
def invert
inverse_class.new(inverse_name, child_model, parent_model, inverted_options)
end
# TODO: document
# @api private
def inverted_options
options.only(*OPTIONS - [ :min, :max ]).update(:inverse => self)
end
# TODO: document
# @api private
def kind_of_inverse?(other)
other.kind_of?(inverse_class)
end
# TODO: document
# @api private
def cmp?(other, operator)
name.send(operator, other.name) &&
cmp_repository?(other, operator, :child) &&
cmp_repository?(other, operator, :parent) &&
cmp_model?(other, operator, :child) &&
cmp_model?(other, operator, :parent) &&
cmp_key?(other, operator, :child) &&
cmp_key?(other, operator, :parent) &&
query.send(operator, other.query)
end
# TODO: document
# @api private
def cmp_repository?(other, operator, type)
# if either repository is nil, then the relationship is relative,
# and the repositories are considered equivalent
return true unless repository_name = send("#{type}_repository_name")
return true unless other_repository_name = other.send("#{type}_repository_name")
repository_name.send(operator, other_repository_name)
end
# TODO: document
# @api private
def cmp_model?(other, operator, type)
send("#{type}_model?") &&
other.send("#{type}_model?") &&
send("#{type}_model").base_model.send(operator, other.send("#{type}_model").base_model)
end
# TODO: document
# @api private
def cmp_key?(other, operator, type)
property_method = "#{type}_properties"
self_key = send(property_method)
other_key = other.send(property_method)
self_key.send(operator, other_key)
end
end # class Relationship
end # module Associations
end # module DataMapper
|
module Renderable
module InstanceMethods
private
def renderable_render
suff = renderable_options[:suffix]
renderable_options[:fields].each do |field|
# skip if the field is unchanged
next unless self.changed.include? field.to_s
# actually render
run_callbacks(:render) do
run_callbacks(:"#{field}_render") do
# a. call out
content = self[field.to_sym]
content = content.nil? ? nil : RedCloth.new(content, renderable_options[:restrictions]).to_html
# b. if we're using RedCloth's lite_mode, let's make the HTML sane again...
if renderable_options[:restrictions].include?(:lite_mode)
# for reasons best known to RedCloth, lite_mode replaces all newlines with a BR tag. This is butt-ugly and
# we can do better.
#
# So, let's find all instances of multiple BRs and replace them with Ps.
content = '<p>'+content.gsub( /(<br\s?\/?>\n){2,}/, "</p>\n\n<p>" )+'</p>';
end
# c. copy it back
self["#{field}#{suff}".to_sym] = content
end
end
end
end
end
end
|
require "test_helper"
require "application_system_test_case"
class CompaniesControllerTest < ApplicationSystemTestCase
def setup
@company = companies(:hometown_painting)
end
test "Index" do
visit companies_path
assert_text "Companies"
assert_text "Hometown Painting"
assert_text "Wolf Painting"
end
test "Show" do
visit company_path(@company)
assert_text @company.name
assert_text @company.phone
assert_text @company.email
assert_text "Ventura, California(CA)"
end
test "Update" do
visit edit_company_path(@company)
within("form#edit_company_#{@company.id}") do
fill_in("company_name", with: "Updated Test Company")
fill_in("company_zip_code", with: "37201")
click_button "Update Company"
end
@company.reload
assert_text "Changes Saved"
assert_equal "Updated Test Company", @company.name
assert_equal "37201", @company.zip_code
assert_equal "Nashville, Tennessee(TN)", @company.address
end
test "Create with valid email domain" do
visit new_company_path
within("form#new_company") do
fill_in("company_name", with: "New Test Company")
fill_in("company_zip_code", with: "28173")
fill_in("company_phone", with: "5553335555")
fill_in("company_email", with: "new_test_company@getmainstreet.com")
click_button "Create Company"
end
assert_text "Saved"
last_company = Company.last
assert_equal "New Test Company", last_company.name
assert_equal "28173", last_company.zip_code
end
test "create should not work with non getmainstreet domain email" do
visit new_company_path
within("form#new_company") do
fill_in("company_name", with: "New Test Company")
fill_in("company_zip_code", with: "28173")
fill_in("company_phone", with: "5553335555")
fill_in("company_email", with: "new_test_company@somemail.com")
click_button "Create Company"
end
assert_text "Email should be with domain getmainstreet.com"
end
test "create with blank email" do
visit new_company_path
within("form#new_company") do
fill_in("company_name", with: "New Test Company")
fill_in("company_zip_code", with: "28173")
fill_in("company_phone", with: "5553335555")
click_button "Create Company"
end
assert_text "Saved"
last_company = Company.last
assert_equal "New Test Company", last_company.name
assert_equal "28173", last_company.zip_code
end
test "Destroy" do
visit company_path(@company)
assert_text "Hometown Painting"
accept_alert do
click_on "Destroy"
end
assert_text "Successfully Deleted"
assert_no_text "Hometown Painting"
end
end
|
class Booking < ApplicationRecord
belongs_to :user
belongs_to :idea
has_many :reviews
validates :start_date, presence: true
validates :end_date, presence: true
validates :request_message, presence: true, length: { minimum: 10 }
end
#comment
|
require File.dirname(__FILE__) + "/../spec_helper"
describe Preflight::Rules::PageCount do
it "should pass files with correct page count specified by Fixnum" do
filename = pdf_spec_file("pdfx-1a-subsetting")
ohash = PDF::Reader::ObjectHash.new(filename)
rule = Preflight::Rules::PageCount.new(1)
rule.check_hash(ohash).should be_empty
end
it "should fail files with incorrect page count specified by Fixnum" do
filename = pdf_spec_file("pdfx-1a-subsetting")
ohash = PDF::Reader::ObjectHash.new(filename)
rule = Preflight::Rules::PageCount.new(2)
rule.check_hash(ohash).should_not be_empty
end
it "should pass files with correct page count specified by range" do
filename = pdf_spec_file("pdfx-1a-subsetting")
ohash = PDF::Reader::ObjectHash.new(filename)
rule = Preflight::Rules::PageCount.new(1..2)
rule.check_hash(ohash).should be_empty
end
it "should fail files with incorrect page count specified by range" do
filename = pdf_spec_file("pdfx-1a-subsetting")
ohash = PDF::Reader::ObjectHash.new(filename)
rule = Preflight::Rules::PageCount.new(2..3)
rule.check_hash(ohash).should_not be_empty
end
it "should pass files with correct page count specified by array" do
filename = pdf_spec_file("pdfx-1a-subsetting")
ohash = PDF::Reader::ObjectHash.new(filename)
rule = Preflight::Rules::PageCount.new([1, 2])
rule.check_hash(ohash).should be_empty
end
it "should fail files with incorrect page count specified by array" do
filename = pdf_spec_file("pdfx-1a-subsetting")
ohash = PDF::Reader::ObjectHash.new(filename)
rule = Preflight::Rules::PageCount.new([2, 3])
rule.check_hash(ohash).should_not be_empty
end
it "should pass files with correct page count specified by :odd" do
filename = pdf_spec_file("pdfx-1a-subsetting")
ohash = PDF::Reader::ObjectHash.new(filename)
rule = Preflight::Rules::PageCount.new(:odd)
rule.check_hash(ohash).should be_empty
end
it "should fail files with correct page count specified by :odd" do
filename = pdf_spec_file("two_pages")
ohash = PDF::Reader::ObjectHash.new(filename)
rule = Preflight::Rules::PageCount.new(:odd)
rule.check_hash(ohash).should_not be_empty
end
it "should pass files with correct page count specified by :even" do
filename = pdf_spec_file("two_pages")
ohash = PDF::Reader::ObjectHash.new(filename)
rule = Preflight::Rules::PageCount.new(:even)
rule.check_hash(ohash).should be_empty
end
it "should fail files with correct page count specified by :even" do
filename = pdf_spec_file("pdfx-1a-subsetting")
ohash = PDF::Reader::ObjectHash.new(filename)
rule = Preflight::Rules::PageCount.new(:even)
rule.check_hash(ohash).should_not be_empty
end
end
|
require 'rails_helper'
RSpec.describe 'merchant show page', type: :feature do
describe 'As a merchant employee' do
before :each do
@mike = Merchant.create!(name: "Mike's Print Shop", address: '123 Paper Rd.', city: 'Denver', state: 'CO', zip: 80203)
@meg = Merchant.create!(name: "Meg's Bike Shop", address: '123 Bike Rd.', city: 'Denver', state: 'CO', zip: 80203)
@tire = @meg.items.create(name: "Gatorskins", description: "They'll never pop!", price: 100, image: "https://www.rei.com/media/4e1f5b05-27ef-4267-bb9a-14e35935f218?size=784x588", inventory: 12)
@paper = @mike.items.create(name: "Lined Paper", description: "Great for writing on!", price: 20, image: "https://cdn.vertex42.com/WordTemplates/images/printable-lined-paper-wide-ruled.png", inventory: 3)
@pencil = @mike.items.create(name: "Yellow Pencil", description: "You can write on paper with it!", price: 2, image: "https://images-na.ssl-images-amazon.com/images/I/31BlVr01izL._SX425_.jpg", inventory: 100)
end
describe "When I visit my merchant dashboard('/merchant')" do
it "I see the name and full address of the merchant I work for" do
allow_any_instance_of(ApplicationController).to receive(:current_user).and_return(@meg)
visit '/merchant'
expect(page).to have_content("\nMeg's Bike Shop\n123 Bike Rd.\nDenver, CO, 80203")
end
end
end
end
|
require "minitest_helper"
describe LevelEditor::ObjectManager do
before do
@image_interroger = LevelEditor::ImageInterroger.new("images/test_case_4.bmp")
@object_manager = LevelEditor::ObjectManager.new(@image_interroger)
end
describe "poisons" do
it "no poison = empty array" do
@object_manager.poisons.must_be_empty
end
it "can find the poisons" do
scan_poisons
@object_manager.poisons.count.must_equal(3)
end
it "can have the coordinates of poisons" do
scan_poisons
@object_manager.poisons.must_equal([[0,0],[1,1],[3,2]])
end
def scan_poisons
@object_manager.scan_pixel(0,0)
@object_manager.scan_pixel(3,2)
@object_manager.scan_pixel(1,1)
end
end
describe "croissant" do
it "can find croissants" do
@object_manager.scan_pixel(1,0)
@object_manager.croissants.count.must_equal(1)
end
end
describe "milkery" do
it "can find a milkeries" do
@object_manager.scan_pixel(3,0)
@object_manager.milkeries.count.must_equal(1)
end
end
end
|
class WorldMusicYamahaRankService < ExperimentService
class << self
SONGS = 10
PAIRS = (0...SONGS).to_a.combination(3).to_a
def create(options)
raise NotFoundError.new('Experiment', 'Evaluation Not Finished') if Experiment.where(
username: options['username'],
model: 'WorldMusicYamahaEvaluationEntry',
)&.first.nil?
DB.transaction do
exp = Experiment.create(
username: options['username'],
model: 'WorldMusicYamahaRankEntry',
)
PAIRS.length.times.to_a.shuffle.each do |i|
WorldMusicYamahaRankEntry.create(
experiment: exp,
pair_id: i,
)
end
return WorldMusicYamahaRankService.new(exp)
end
end
def find(options)
exp = Experiment.where(
username: options['username'],
model: 'WorldMusicYamahaRankEntry',
)&.first
raise NotFoundError.new('Experiment', 'No Such Experiment Existed') if exp.nil?
WorldMusicYamahaRankService.new(exp)
end
def export
Experiment.where(
model: 'WorldMusicYamahaRankEntry',
).map do |exp|
res = exp.entries.order(:pair_id).map do |pair|
{
song_a: PAIRS[pair.pair_id][0],
song_b: PAIRS[pair.pair_id][1],
song_c: PAIRS[pair.pair_id][2],
option: pair.option,
}
end
{
username: exp.username,
matrix: res,
}
end
end
end
def initialize(entity)
@entity = entity
end
def offset
cat = @entity.username[-1].to_i
raise NotFoundError.new('Entity', 'No Such Category') unless (0...4).include?(cat) # 4 Groups
@entity.username[-1].to_i * 5
end
def next
entity = @entity.entries.where(edited: false).order(:id).first
raise NotFoundError.new('Entity', 'Experiment Finished') if entity.nil?
{
id: entity.id,
progress: @entity.entries.where(edited: true).count.to_f / @entity.entries.count,
wavs: [
{
label: 'A',
entity: "/static/world_music_workshop/#{WorldMusicYamahaRankService.singleton_class::PAIRS[entity.pair_id][0] + offset}.mp3",
},
{
label: 'B',
entity: "/static/world_music_workshop/#{WorldMusicYamahaRankService.singleton_class::PAIRS[entity.pair_id][1] + offset}.mp3",
},
{
label: 'C',
entity: "/static/world_music_workshop/#{WorldMusicYamahaRankService.singleton_class::PAIRS[entity.pair_id][2] + offset}.mp3",
},
],
}
end
def update(options)
entry = @entity.entries.where(id: options['id'])&.first
raise NotFoundError.new('Entry Not Existed') if entry.nil?
entry.option = options['option']
entry.edited = true
entry.save
nil
end
def destroy
@entity.entries.delete
@entity.delete
end
end
|
module WsdlMapper
module Dom
class Bounds
attr_accessor :min, :max, :nillable
def initialize(min: nil, max: nil, nillable: nil)
@min, @max, @nillable = min, max, nillable
end
def dup
Bounds.new min: @min, max: @max, nillable: @nillable
end
end
end
end
|
# === COPYRIGHT:
# Copyright (c) Jason Adam Young
# === LICENSE:
# see LICENSE file
class UpdateStatsJob < ApplicationJob
queue_as :default
def perform(season_id)
begin
season = Season.find(season_id)
rescue ActiveRecord::RecordNotFound => error
Sentry.capture_exception(error)
return false
end
# raise SeasonError unless season.ready_for_stats?
if(!season.ready_for_stats?)
SlackIt.post(message: "Not ready to process stats - Season state: #{season.state}")
return true
end
season.process_stats!
SlackIt.post(message: "Starting processing stats for season #{season.season_year}")
Team.update_batting_stats_for_season_year(season.season_year)
BattingStat.update_total_batting_stats_for_season_year(season.season_year)
Team.update_pitching_stats_for_season_year(season.season_year)
PitchingStat.update_total_pitching_stats_for_season_year(season.season_year)
# update playing time
Roster.create_or_update_playing_time_for_season_year(season.season_year)
SlackIt.post(message: "Finished processing stats for season #{season.season_year}")
season.processed_stats!
end
end |
class TrendingGroupsRefreshWorker
include Sidekiq::Worker
include Sidetiq::Schedulable
# Because minutely(int) is slow as balls
# See tobiassvn/sidetiq#31
recurrence { hourly.minute_of_hour(00, 05, 10, 15, 20, 25,
30, 35, 40, 45, 50, 55) }
def perform
TrendingGroup.connection.execute('REFRESH MATERIALIZED VIEW trending_groups')
end
end
|
module Hexagonal
class Repository
attr_writer :database_klass, :adapter
def all
adapter.all
end
def find(id)
adapter.find id
end
def save(object)
adapter.save(object)
end
def save!(object)
adapter.save!(object)
end
def destroy(object)
adapter.destroy(object)
end
def unit_of_work
adapter.unit_of_work
end
private
def adapter
@adapter ||= Hexagonal::Adapters::ActiveRecordAdapter.new(database_klass)
end
end
end
|
class TransactionsController < ApplicationController
before_action :set_transaction, only: [:show]
def show
end
private
def set_transaction
@transaction = Transaction.find(params[:id])
end
end |
require 'bcrypt'
class User < ActiveRecord::Base
validates :email, presence: true
validates :email, uniqueness: true
validates_format_of :email, :with => /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\Z/i
validates :password, presence: true
include BCrypt
def password
@password ||= Password.new(password_hash)
end
def password=(new_password)
@password = Password.create(new_password)
self.password_hash = @password
end
def self.authenticate(email, password_attempt)
# if email and password correspond to a valid user, return that user
# otherwise, return nil
@user = User.find_by email: email
if @user && @user.password == password_attempt
return @user
end
nil
end
def get_name
self.first_name
end
end
|
class AddIndexToAreas < ActiveRecord::Migration
def up
add_index :areas, [ :areable_type, :areable_id, :area_category_id ], unique: true
end
def down
remove_index :areas, [ :areable_type, :areable_id, :area_category_id ], unique: true
end
end
|
class Place < ApplicationRecord
belongs_to :user
has_many :comments
has_many :photos
geocoded_by :address
after_validation :geocode
validates :name, length: { minimum: 2, too_long: "%{count} Character is the maximum allowed" }, presence: true
validates :address, presence: true
validates :description, length: { maximum: 200, too_long: "%{count} Character is the maximum allowed" }, presence: true
end
|
class EntryController < ApplicationController
def index
@entries = Entry.includes(:user)
@entriess = Entry.all.order("created_at DESC")
# @entry = Entry.find(params[:id])
# @user = User.find(params[:user_id])
end
def new
@entry = Entry.new
end
def create
@entry = Entry.new(entry_params)
if @entry.save
redirect_to root_path
else
render new_entry_path
end
end
def show
@entry = Entry.find(params[:id])
@comment = Comment.new
@comments = @entry.comments.includes(:user)
end
def muscle
@all_ranks = Entry.find(Like.group(:entry_id).order('count(entry_id) desc').limit(9).pluck(:entry_id))
end
def edit
@entry = Entry.find(params[:id])
end
def update
@entry = Entry.find(params[:id])
if @entry.update(entry_params)
redirect_to root_path
else
render :edit
end
end
def destroy
entry = Entry.find(params[:id])
entry.destroy
redirect_to root_path
end
private
def entry_params
params.require(:entry).permit(:title,:image,:entrycategory_id,:text,category_ids: []).merge(user_id: current_user.id)
end
end
|
class ApiController < ActionController::Base
skip_before_action :verify_authenticity_token
before_action :check_token
private
def check_token
render json: { error: 'Invalid auth token' }, status: 401 unless current_user
end
def current_user
token = request.headers['App-Token']
User.where(token: token).first
end
helper_method :current_user
end
|
class UserMailer < ActionMailer::Base
default from: "from@example.com"
def sample_email(user, article)
@user = user
@article = article
puts @user
mail(to: @user.email, subject: "#{@article.title}")
end
end
|
class AddRoomsCountToInstances < ActiveRecord::Migration[5.2]
def change
add_column :instances, :rooms_count, :integer
Instance.find_each do |instance|
Instance.reset_counters(instance.id, :rooms)
end
end
end
|
class ChartDoneRatio < ActiveRecord::Base
def self.get_timeline_for_issue(raw_conditions, range)
conditions = {}
done_ratios = {}
raw_conditions.each do |c, v|
column_name = RedmineCharts::ConditionsUtils.to_column(c, "chart_done_ratios")
conditions[column_name] = v if v and column_name
end
range = RedmineCharts::RangeUtils.prepare_range(range)
range[:column] = RedmineCharts::ConditionsUtils.to_column(range[:range], "chart_done_ratios")
joins = "left join issues on issues.id = issue_id"
conditions[range[:column]] = range[:min]..range[:max]
select = "#{range[:column]} as range_value, '#{range[:range]}' as range_type, chart_done_ratios.done_ratio, chart_done_ratios.issue_id"
rows = all(:select => select, :joins => joins, :conditions => conditions, :order => '1 asc')
rows.each do |row|
done_ratios[row.issue_id.to_i] ||= Array.new(range[:keys].size, 0)
index = range[:keys].index(row.range_value.to_s)
next unless index
(index...range[:keys].size).each do |i|
done_ratios[row.issue_id.to_i][i] = row.done_ratio.to_i
end
end
latest_done_ratio = get_aggregation_for_issue(raw_conditions)
latest_done_ratio.each do |issue_id, done_ratio|
done_ratios[issue_id] ||= Array.new(range[:keys].size, done_ratio)
end
done_ratios
end
def self.get_aggregation_for_issue(raw_conditions)
conditions = {}
conditions[:project_id] = raw_conditions[:project_ids]
conditions[:day] = 0
conditions[:week] = 0
conditions[:month] = 0
rows = all(:conditions => conditions)
issues = {}
rows.each do |row|
issues[row.issue_id.to_i] = row.done_ratio.to_i
end
issues
end
end
|
require 'json'
require 'jsonpath'
require 'rest-client'
module CucumberApi
# Extension of {RestClient::Response} with support for JSON path traversal and validation
module Response
# Create a Response with JSON path support
# @param response [RestClient::Response] original response
# @return [Response] self
def self.create response
result = response
result.extend Response
result
end
# Check if given JSON path exists
# @param json_path [String] a valid JSON path expression
# @param json [String] optional JSON from which to check JSON path, default to response body
# @return [true, false] true if JSON path is valid and exists, false otherwise
def has json_path, json=nil
if json.nil?
json = JSON.parse body
end
not JsonPath.new(json_path).on(json).empty?
end
# Retrieve value of the first JSON element with given JSON path
# @param json_path [String] a valid JSON path expression
# @param json [String] optional JSON from which to apply JSON path, default to response body
# @return [Object] value of first retrieved JSON element in form of Ruby object
# @raise [Exception] if JSON path is invalid or no matching JSON element found
def get json_path, json=nil
if json.nil?
json = JSON.parse body
end
results = JsonPath.new(json_path).on(json)
if results.empty?
raise %/Expected json path '#{json_path}' not found\n#{to_json_s}/
end
results.first
end
# Retrieve value of the first JSON element with given JSON path as given type
# @param json_path [String] a valid JSON path expression
# @param type [String] required type, possible values are 'numeric', 'array', 'string', 'boolean', 'numeric_string'
# or 'object'
# @param json [String] optional JSON from which to apply JSON path, default to response body
# @return [Object] value of first retrieved JSON element in form of given type
# @raise [Exception] if JSON path is invalid or no matching JSON element found or matching element does not match
# required type
def get_as_type json_path, type, json=nil
value = get json_path, json
case type
when 'numeric'
valid = value.is_a? Numeric
when 'array'
valid = value.is_a? Array
when 'string'
valid = value.is_a? String
when 'boolean'
valid = !!value == value
when 'numeric_string'
valid = value.is_a?(Numeric) or value.is_a?(String)
when 'object'
valid = value.is_a? Hash
else
raise %/Invalid expected type '#{type}'/
end
unless valid
raise %/Expect '#{json_path}' as a '#{type}' but was '#{value.class}'\n#{to_json_s}/
end
value
end
# Retrieve value of the first JSON element with given JSON path as given type, with nil value allowed
# @param json_path [String] a valid JSON path expression
# @param type [String] required type, possible values are 'numeric', 'array', 'string', 'boolean', 'numeric_string'
# or 'object'
# @param json [String] optional JSON from which to apply JSON path, default to response body
# @return [Object] value of first retrieved JSON element in form of given type or nil
# @raise [Exception] if JSON path is invalid or no matching JSON element found or matching element does not match
# required type
def get_as_type_or_null json_path, type, json=nil
value = get json_path, json
value.nil? ? value : get_as_type(json_path, type, json)
end
# Retrieve value of the first JSON element with given JSON path as given type, and check for a given value
# @param json_path [String] a valid JSON path expression
# @param type [String] required type, possible values are 'numeric', 'string', 'boolean', or 'numeric_string'
# @param value [String] value to check for
# @param json [String] optional JSON from which to apply JSON path, default to response body
# @return [Object] value of first retrieved JSON element in form of given type or nil
# @raise [Exception] if JSON path is invalid or no matching JSON element found or matching element does not match
# required type or value
def get_as_type_and_check_value json_path, type, value, json=nil
v = get_as_type json_path, type, json
if value != v.to_s
raise %/Expect '#{json_path}' to be '#{value}' but was '#{v}'\n#{to_json_s}/
end
end
# Retrieve pretty JSON response for logging
# @return [String] pretty JSON response if verbose setting is true, empty string otherwise
def to_json_s
if ENV['cucumber_api_verbose'] == 'true'
JSON.pretty_generate(JSON.parse to_s)
else
''
end
end
RestClient::Response.send(:include, self)
end
end
|
require 'spec_helper'
describe OrgSpacePolicy do
let(:org_guid) { "my_org" }
let(:space_guid) { "my_space" }
let(:policy_name) { 'cf' }
subject { OrgSpacePolicy.new(org_guid, space_guid, nil, nil) }
before do
allow(ConjurClient).to receive(:policy).and_return(policy_name)
allow(ConjurClient).to receive(:login_host_id).and_return('service-broker')
allow(ENV).to receive(:[]).and_call_original
end
let(:create_policy_body) do
<<~YAML
---
- !policy
id: #{org_guid}
body:
- !layer
- !policy
id: #{space_guid}
body:
- !layer
- !grant
role: !layer
member: !layer #{space_guid}
YAML
end
describe "#create" do
context "when org and space names are not available from Service Broker API" do
it "loads Conjur policy to create the org and space policy without annotations" do
expect_any_instance_of(Conjur::API).
to receive(:load_policy).
with(policy_name, create_policy_body, method: :post)
subject.create
end
end
end
describe "#ensure_exists" do
let(:existent_resource) { double("existent", exists?: true) }
let(:nonexistent_resource) { double("non-existent", exists?: false) }
before do
# By default, assume all resources exist
allow_any_instance_of(Conjur::API)
.to receive(:resource)
.with(any_args)
.and_return(existent_resource)
end
context "when resources already exist" do
it "does not raise an error" do
expect { subject.ensure_exists }.not_to raise_error
end
end
context "when org policy doesn't exist" do
before do
allow_any_instance_of(Conjur::API)
.to receive(:resource)
.with("cucumber:policy:#{policy_name}/#{org_guid}").
and_return(nonexistent_resource)
end
it "raises an error" do
expect { subject.ensure_exists }.to raise_error(OrgSpacePolicy::OrgPolicyNotFound)
end
end
context "when space policy doesn't exist" do
before do
allow_any_instance_of(Conjur::API)
.to receive(:resource)
.with("cucumber:policy:#{policy_name}/#{org_guid}/#{space_guid}")
.and_return(nonexistent_resource)
end
it "raises an error" do
expect { subject.ensure_exists }.to raise_error(OrgSpacePolicy::SpacePolicyNotFound)
end
end
context "when space layer doesn't exist" do
before do
allow_any_instance_of(Conjur::API)
.to receive(:resource)
.with("cucumber:layer:#{policy_name}/#{org_guid}/#{space_guid}")
.and_return(nonexistent_resource)
end
it "raises and error" do
expect { subject.ensure_exists }.to raise_error(OrgSpacePolicy::SpaceLayerNotFound)
end
end
end
end
|
describe Treasury::Fields::HashOperations do
let(:hash_field_class) do
Class.new do
include Treasury::Fields::HashOperations
extend Treasury::HashSerializer
end
end
describe "#value_as_hash" do
let(:value_as_hash) { hash_field_class.value_as_hash(object: 123, field: :count) }
before do
allow(hash_field_class).to receive(:value).and_return(value)
end
context 'when values is ints' do
let(:value) { '10:100,20:200' }
it do
expect(hash_field_class).to receive(:init_accessor).with(object: 123, field: :count)
expect(value_as_hash).to eq('10' => 100, '20' => 200)
end
end
context 'when values is dates' do
let(:value) { '10:2019-12-31,20:1999-10-01,21:2020-01-20' }
it do
expect(hash_field_class).to receive(:init_accessor).with(object: 123, field: :count)
expect(value_as_hash).to eq(
'10' => Date.parse('2019-12-31'),
'20' => Date.parse('1999-10-01'),
'21' => Date.parse('2020-01-20')
)
end
end
context 'when values is strings' do
let(:value) { '10:8888-12-31,20:foobar' }
it do
expect(hash_field_class).to receive(:init_accessor).with(object: 123, field: :count)
expect(value_as_hash).to eq('10' => '8888-12-31', '20' => 'foobar')
end
end
end
end
|
require 'colorize'
require 'artii'
class Question
attr_accessor :prompt, :answer
def initialize(prompt, answer)
@prompt = prompt
@answer = answer
end
end
def clear_terminal
system("clear")
end
def run_quiz test
answer = ""
score = 0
appname = Artii::Base.new
for question in test
clear_terminal
puts question.prompt.colorize(:yellow)
answer = gets.chomp()
until (answer == 'a' or answer == 'b'or answer =='c')
clear_terminal
puts question.prompt.colorize(:yellow)
puts "Please enter a, b or c"
answer = gets.chomp()
end
if answer == question.answer
score += 1
end
end
clear_terminal
puts "Congratulations! You got #{score} from 3 for this Topic"
puts "If you would like to try another topic, Press 'y'. To Quit press any other key."
toquit = gets.chomp
if toquit == "y"
else
clear_terminal
puts appname.asciify("B Y E B Y E")
puts "Thank you for playing Quiz_T1A2. Have a nice day =)"
exit
end
end
tempARGV = ARGV
help = tempARGV[0]
ARGV.clear
if help == "-h"
clear_terminal
exec 'cat "help.md"'
end
p1 = "What year was the first Star Wars movie, A New Hope released?\n(a)1977\n(b)1981\n(c)1984"
p2 = "What is Arnold Schwarzenegger's most famous role? \n(a)Conan\n(b)The Terminator\n(c)Dutch"
p3 = "What animal is Nemo from the movie Finding Nemo? \n(a)Dog\n(b)Rabbit\n(c)Fish"
p4 = "What song has spent the most time on Billboards Number 1 Spot? \n(a)Despacito\n(b)Old Town Road\n(c)One Sweet Day"
p5 = "Which artist has the most Number 1 singles? \n(a)Elvis Presley\n(b)Michael Jackson\n(c)The Beatles"
p6 = "What is the most sold album world wide?\n(a)Back in Black by AC/DC\n(b)Thriller by Michael Jackson\n(c)Bat out of Hell by Meatloaf"
p7 = "What is the most sold gaming console of all time?\n(a)Xbox 360\n(b)Nintendo Wii\n(c)Playstation 2"
p8 = "Who is the most recognised video game character of all time?\n(a)Mario\n(b)Solid Snake\n(c)Pac-Man"
p9 = "How many ghosts are there in Pac-Man?\n(a)2\n(b)3\n(c)4"
movie_questions = [
Question.new(p1, 'a'),
Question.new(p2, 'b'),
Question.new(p3, 'c')
]
music_questions = [
Question.new(p4, 'b'),
Question.new(p5, 'c'),
Question.new(p6, 'b')
]
gaming_questions = [
Question.new(p7, 'c'),
Question.new(p8, 'a'),
Question.new(p9, 'c')
]
if help == "movies"
test = movie_questions
run_quiz(test)
exit
end
if help == "music"
test = music_questions
run_quiz(test)
exit
end
if help == "gaming"
test = gaming_questions
run_quiz(test)
exit
end
appname = Artii::Base.new
clear_terminal
puts appname.asciify("Q u i z T 1 A 2")
puts "Welcome to Quiz_T1A2 =) Please enter your name...".colorize(:light_blue)
name = gets.chomp.to_s
topic_array = ['Movies','Music','Gaming']
clear_terminal
puts "Hi #{name}, Please choose a Category.\n(1)#{topic_array[0]}\n(2)Music\n(3)Gaming".colorize(:magenta)
user_input = gets.chomp
test = ""
if user_input == '1'
test = movie_questions
run_quiz(test)
elsif user_input == '2'
test = music_questions
run_quiz(test)
elsif user_input == '3'
test = gaming_questions
run_quiz(test)
end
begin
if user_input > '3'
run_quiz()
end
rescue ArgumentError
puts "Critical Error... Forced to Shutdown"
exit
end
def next_topic(user_input, topic_array)
if user_input == '1'
topic_array[0] = "Movies (You've already completed this)"
elsif user_input == '2'
topic_array[1] = "Music (You've already completed this)"
elsif user_input == '3'
topic_array[2] = "Gaming (You've already completed this)"
end
user_input = ""
end
next_topic(user_input, topic_array)
puts "Which of the remaining Topics would you like to do?"
puts "(1)#{topic_array[0]}\n(2)#{topic_array[1]}\n(3)#{topic_array[2]}".colorize(:magenta)
user_input = gets.chomp
test = ""
if user_input == '1'
test = movie_questions
run_quiz(test)
elsif user_input == '2'
test = music_questions
run_quiz(test)
elsif user_input == '3'
test = gaming_questions
run_quiz(test)
elsif user_input != ('1' or '2' or '3')
puts "Error... Terminating App. Please restart and select the category with the number 1 2 or 3"
end
next_topic(user_input, topic_array)
puts "(1)#{topic_array[0]}\n(2)#{topic_array[1]}\n(3)#{topic_array[2]}".colorize(:red)
result = topic_array.reject{|item| item.include?("completed")}
clear_terminal
puts "#{result} is the last topic of this Application. Goodluck #{name}!"
if result == ["Movies"]
test = movie_questions
run_quiz(test)
elsif result == ["Music"]
test = music_questions
run_quiz(test)
elsif result == ["Gaming"]
test = gaming_questions
run_quiz(test)
end
clear_terminal
puts "Thank you #{name} for playing Quiz_T1A2. Have a nice day =)"
puts appname.asciify("B Y E B Y E")
|
require 'spec_helper'
describe Postmark::Inflector do
describe ".to_postmark" do
it 'converts rubyish underscored format to camel cased symbols accepted by the Postmark API' do
subject.to_postmark(:foo_bar).should == 'FooBar'
subject.to_postmark(:_bar).should == 'Bar'
subject.to_postmark(:really_long_long_long_long_symbol).should == 'ReallyLongLongLongLongSymbol'
subject.to_postmark(:foo_bar_1).should == 'FooBar1'
end
it 'accepts strings as well' do
subject.to_postmark('foo_bar').should == 'FooBar'
end
it 'acts idempotentely' do
subject.to_postmark('FooBar').should == 'FooBar'
end
end
describe ".to_ruby" do
it 'converts camel cased symbols returned by the Postmark API to underscored Ruby symbols' do
subject.to_ruby('FooBar').should == :foo_bar
subject.to_ruby('LongTimeAgoInAFarFarGalaxy').should == :long_time_ago_in_a_far_far_galaxy
subject.to_ruby('MessageID').should == :message_id
end
it 'acts idempotentely' do
subject.to_ruby(:foo_bar).should == :foo_bar
subject.to_ruby(:foo_bar_1).should == :foo_bar_1
end
end
end |
class Profile::FolderEmailsController < Profile::ProfileController
before_filter :set_folder, only: [:new, :create]
def new
@folder_email = FolderEmail.new({
subject: current_user.username + FolderEmail::DEFAULT_SUBJECT,
over: params[:over] == 'true'
})
render layout: 'layouts/popup' if @folder_email.over
end
def create
@folder_email = FolderEmail.new(params[:folder_email])
@folder_email.user = current_user
@folder_email.folder = @folder
if @folder_email.save
recipients = @folder_email.recipient.split(',')
cc = true
recipients.each do |recipient|
if is_email(recipient.strip)
FolderMailer.delay(queue: 'folder_mailer')\
.send_to_friend(@folder_email, recipient.strip, cc)
cc = false
else
logger.info "\n\n\n--- You can't fool me! #{recipient} \n\n"
end
end
redirect_to new_profile_folder_folder_email_path(@folder,
over: (@folder_email.over ? "true" : "")),
notice: "Your email has been sent"
elsif @folder_email.over == true || @folder_email.over == 'true'
render :new
else
render :new
end
end
def is_email(str)
str.match(/^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/i)
end
private
def set_folder
@folder = current_user.folders.find_by_id!(params[:folder_id])
end
end
|
require 'spec_helper'
describe Sonar::Connector::SonarPushConnector do
before do
setup_valid_config_file
@base_config = Sonar::Connector::Config.load(valid_config_filename)
end
# @connector = Sonar::Connector::SonarPushConnector.new
def simple_config(opts={})
{
'name'=>'foobarcom-sonarpush',
'repeat_delay'=>60,
'uri'=>"https://foobar.com/api/1_0/json_messages",
'connector_credentials'=>"0123456789abcdef",
'source_connectors'=>['foo'],
'batch_size'=>10,
'delete'=>true
}.merge(opts)
end
describe "action" do
it "should call filestore.process_batch with :working as source and error dirs" do
c=Sonar::Connector::SonarPushConnector.new(simple_config, @base_config)
c.instance_eval{@filestore = Object.new}
source_connectors = [Object.new]
mock(c).source_connectors{source_connectors}
mock(source_connectors[0]).connector_filestore.mock!.flip(:complete, c.filestore, :working)
mock(c.filestore).process_batch.with_any_args{ |size, source, error, success, block|
size.should == 10
source.should == :working
error.should == :working
success.should == nil
0
}
c.action
end
it "should call filestore.process_batch with a success area of :complete if !delete" do
c=Sonar::Connector::SonarPushConnector.new(simple_config("delete"=>false), @base_config)
c.delete.should == false
c.instance_eval{@filestore = Object.new}
source_connectors = [Object.new]
mock(c).source_connectors{source_connectors}
mock(source_connectors[0]).connector_filestore.mock!.flip(:complete, c.filestore, :working)
mock(c.filestore).process_batch.with_any_args{ |size, source, error, success, block|
size.should == 10
source.should == :working
error.should == :working
success.should == :complete
0
}
c.action
end
it "should catch exceptions during push, and raise LeaveInSourceArea" do
c=Sonar::Connector::SonarPushConnector.new(simple_config, @base_config)
c.instance_eval{@filestore = Object.new}
source_connectors = [Object.new]
mock(c).source_connectors{source_connectors}
mock(source_connectors[0]).connector_filestore.mock!.flip(:complete, c.filestore, :working)
root = "/blah/blah"
files = ["foo/bar", "foo/foo"]
files.each{|file| mock(c.filestore).file_path(:working, file){ "#{root}/working/#{file}" }}
mock(c).push_batch(["/blah/blah/working/foo/bar", "/blah/blah/working/foo/foo"]){raise "boo"}
mock(c.filestore).process_batch.with_any_args{ |size, source, error, success, block|
lambda{
block.call(files)
}.should raise_error(Sonar::Connector::FileStore::LeaveInSourceArea)
0
}
c.action
end
end
end
|
# frozen_string_literal: true
class SlackNotifier
def notify(payload:)
"Will post the following to Slack: #{payload}"
end
end
|
require 'spec_helper'
describe SessionsController do
describe "GET new" do
it "render the new template if user not authenticated" do
get :new
response.should render_template :new
end
it "redirect to video home if user authenticated " do
session[:user_id] = Fabricate(:user).id
get :new
response.should redirect_to home_path
end
end
describe "POST create" do
context "with valid credentials" do
before do
@chris = Fabricate(:user)
post :create, email: @chris.email, password: @chris.password
end
it "stores sign in user in the session" do
session[:user_id].should == @chris.id
end
it "redirect to the home path" do
response.should redirect_to home_path
end
#it "sets the notice"
end
context "with invalid crendentials" do
before do
post :create, email: "chris@example.com", password: "5566"
end
it "set notice" do
flash[:error].should == "Invalid email or password."
end
it "redirect to sign_in path" do
response.should redirect_to sign_in_path
end
end
end
describe "GET sign_out" do
it "destroy the session after sign out" do
session[:user_id] = Fabricate(:user).id
get :destroy
session[:user_id].should == nil
end
it "redirect to front page after sign out" do
session[:user_id] = Fabricate(:user).id
get :destroy
response.should redirect_to root_path
end
end
end
|
# Write a method that takes a string as an argument and returns a new string
# in which every uppercase letter is replaced by its lowercase version, and
# every lowercase letter by its uppercase version. All other characters should
# be unchanged.
# You may not use String#swapcase; write your own version of this method.
UPCASE = /[A-Z]/
LOWERCASE = /[a-z]/
def swapcase(str)
new_str = ''
count = 0
loop do
break if str.zeroo? || count == str.length
case str[count]
when UPCASE
new_str += str[count].downcase
when LOWERCASE
new_str += str[count].upcase
else
new_str += str[count]
end
count += 1
end
p new_str
end
p swapcase('CamelCase') == 'cAMELcASE'
p swapcase('Tonight on XYZ-TV') == 'tONIGHT ON xyz-tv'
|
module Sagrone
class Event < Base
attributes :title, :description
validates :title, presence: true
validates :description, presence: true
end
end
|
class Team
attr_accessor :name, :win, :lose, :draw
def initialize(name,win,lose,draw)
self.name = name
self.win = win
self.lose = lose
self.draw = draw
end
def calc_win_rate()
return self.win.to_f / (self.win + self.lose)
end #
def show_team_result()
puts "#{self.name}の2020年の成績は#{self.win}勝 #{self.lose}負 #{self.draw} 勝率は #{calc_win_rate}です。 "
end
end
team_A = Team.new('Giants',67,45,8)
team_B = Team.new('Tigers',60,53,7)
team_C = Team.new('Dragons',60,55,5)
team_D = Team.new('Baystars',56,58,6)
team_E = Team.new('Carp',52,56,12)
team_F = Team.new('Swallows',41,69,10)
team_A.show_team_result()
team_B.show_team_result()
team_C.show_team_result()
team_D.show_team_result()
team_E.show_team_result()
team_F.show_team_result() |
class Admin::UsersController < ApplicationController
before_action :is_admin
before_action :authenticate_user!
def index
if params[:pass].present?
@user = User.find(params[:pass])
@user.update(role: "admin")
end
@users = User.all
end
def edit
@user = User.find(params[:id])
end
def update
@user = User.find(params[:id])
@user.update(strong_params)
redirect_to admin_users_path
end
def destroy
@user = User.find(params[:id])
@user.destroy
redirect_to admin_users_path
end
private
def strong_params
params.require(:user).permit(:introduction, :role)
end
def is_admin
unless current_user.role == "admin"
redirect_to root_path
return
end
end
end
|
class Map
attr_accessor :array
def initialize
@array = []
end
def set(key, val)
idx = find_index(key)
arr = [key, val]
(idx.nil? ? @array.push(arr) : @array[idx][1] = val)
end
def get(key)
idx = find_index(key)
(idx.nil? ? nil : @array[idx].last)
end
def find_index(key)
idx = nil
@array.each_index do |i|
idx = i if @array[i].first == key
end
idx
end
def delete(key)
@array.reject! { |el| el[0] == key }
end
def show
@array
end
end
|
class CreateArranges < ActiveRecord::Migration[5.1]
def change
create_table :arranges do |t|
t.integer :course_id, comment: '课程ID'
t.integer :coach_id, comment: '上课教练ID'
t.datetime :start_time, comment: '开始时间'
t.integer :duration, comment: '课程时长(分钟)'
t.integer :member_count, comment: '上课人数'
t.integer :created_by, comment: '添加人'
t.text :description, comment: '安排描述'
t.integer :is_enable, default: 1, comment: '是否启用'
t.datetime :delete_at, comment: '删除时间'
t.timestamps
end
end
end
|
# -*- coding: utf-8 -*-
require "s7n/entry"
module S7n
# 機密情報の集合を表現する。
class EntryCollection
# 機密情報の配列。
attr_reader :entries
def initialize
@entries = []
@max_id = 0
end
# 機密情報を追加する。
def add_entries(*entries)
[entries].flatten.each do |entry|
@max_id += 1
entry.id = @max_id
@entries.push(entry)
end
end
# 機密情報を削除し、削除した機密情報を返す。
def delete_entries(*entries)
entries = [entries].flatten
deleted_entries = []
@entries.delete_if { |entry|
if entries.include?(entry)
deleted_entries << entry
true
else
false
end
}
return deleted_entries
end
# other で指定した EntryCollection オブジェクトの entries をマージ
# する。
def merge(other)
add_entries(other.entries)
end
# 指定した id にマッチする Entry オブジェクトを entries から探す。
def find(id)
return @entries.find { |entry| entry.id == id }
end
end
end
|
class RemoveColumn < ActiveRecord::Migration[5.1]
def change
remove_column(:employees, :employee_id, :integer)
end
end
|
class Cranky
=begin
# Simple factory method to create a user instance, you would call this via Factory.build(:user)
def user
# Define attributes via a hash, generate the values any way you want
define :name => "Jimmy",
:email => "jimmy#{n}@home.com", # An 'n' counter method is available to help make things unique
:role => "pleb",
:address => default_address # Call your own helper methods to wire up your associations
end
# Easily create variations via the inherit helper, callable via Factory.build(:admin)
def admin
inherit(:user, :role => "admin")
end
# Return a default address if it already exists, or call the address factory to make one
def default_address
@default_address ||= create(:address)
end
# Alternatively loose the DSL altogether and define the factory yourself, still callable via Factory.build(:address)
def address
a = Address.new
a.street = "192 Broadway"
a.city = options[:city] || "New York" # You can get any caller overrides via the options hash
a # Only rule is the method must return the generated object
end
=end
end |
require 'wsdl_mapper/runtime/middlewares/simple_response_factory'
module WsdlMapperTesting
module Middlewares
class FakeResponseFactory < WsdlMapper::Runtime::Middlewares::SimpleResponseFactory
def initialize
@xml = {}
end
def fake_d10r(xml, body)
@xml[xml] = body
end
protected
def deserialize_envelope(operation, response)
response.envelope = @xml[response.body]
end
end
end
end
|
module ZFSProbe
ZFS_SUPER_OFFSET = 0
ZFS_MAGIC_OFFSET = 0
ZFS_MAGIC_SIZE = 4
ZFS_SUPER_MAGIC = 0x00bab10c
def self.probe(dobj)
return(false) unless dobj.kind_of?(MiqDisk)
# Check for magic at uberblock offset.
dobj.seek(ZFS_SUPER_OFFSET + ZFS_MAGIC_OFFSET)
bs = dobj.read(ZFS_MAGIC_SIZE)&.unpack('L')
magic = bs.nil? ? nil : bs[0]
raise "ZFS is Not Supported" if magic == ZFS_SUPER_MAGIC
# No ZFS.
false
end
end
|
module Minitest
module Assertions
def assert_shall_agree_upon contract_name, response
result = response.body
api_service = BlueprintAgreement::DrakovService.new(BlueprintAgreement.configuration)
server = BlueprintAgreement::Server.new(
api_service: api_service,
config: BlueprintAgreement.configuration
)
begin
server.start(contract_name)
request = BlueprintAgreement::RequestBuilder.for(self)
requester = BlueprintAgreement::Utils::Requester.new(request, server)
expected = requester.perform.body.to_s
unless BlueprintAgreement.configuration.exclude_attributes.nil?
filters = BlueprintAgreement.configuration.exclude_attributes
result = BlueprintAgreement::ExcludeFilter.deep_exclude(
BlueprintAgreement::Utils.to_json(result),
filters)
expected = BlueprintAgreement::ExcludeFilter.deep_exclude(
BlueprintAgreement::Utils.to_json(expected),
filters)
end
result = BlueprintAgreement::Utils.response_parser(result)
expected = BlueprintAgreement::Utils.response_parser(expected)
assert_equal expected, result
end
end
end
end
|
FactoryBot.define do
factory :items do
sequence(:title) { |n| "item-#{n}"}
description 'An item'
image 'https://orig00.deviantart.net/1a96/f/2016/022/7/e/random_items_i_drew_for_marapets_by_zhamae-d9ovp9i.png'
price 100
retired? false
end
end |
# This file should contain all the record creation needed to seed the database with its default values.
# The data can then be loaded with the rails db:seed command (or created alongside the database with db:setup).
#
# Examples:
#
# movies = Movie.create([{ name: 'Star Wars' }, { name: 'Lord of the Rings' }])
# Character.create(name: 'Luke', movie: movies.first)
Sport.destroy_all
sports = [
{
name: "basketball",
photo_url: "https://www.sportscorner.qa/image/catalog/Blog/Basketball02.jpg"
},
{
name: "baseball",
photo_url: "http://2.bp.blogspot.com/-GAEriWtMPnk/UKjJZKNONzI/AAAAAAAAEDI/_wpbFtMvA08/s1600/HD-baseball-wallpapers-14.jpg"
},
{
name: "rowing",
photo_url: "http://static1.squarespace.com/static/5529b6d9e4b016252ff27c16/t/5536fcefe4b012ad8a2d4d8c/1429667058893/rowing_crew.jpg?format=1500w"
},
{
name: "football",
photo_url: "http://asfenris.fr/wp-content/uploads/2016/02/background-football.jpg"
},
{
name: "soccer",
photo_url: "https://www.radioscoop.com/imgs/89301_640_360.jpg"
},
{
name: "tennis",
photo_url: "http://www.club.fft.fr/asljltennis/31910022_d/data_1/jpg/ak/aktivurlaubsuedtirol_tennis_1.jpg"
},
{
name: "curling",
photo_url: "http://ekladata.com/8-Zrd9jknHT0RhOuBVdIWWQpOB0.jpg"
},
{
name: "badminton",
photo_url: "http://www.bhbc.fr/wp-content/uploads/2016/07/974746-badminton.jpg"
},
{
name: "horse riding",
photo_url: "http://data.whicdn.com/images/49368827/original.jpg"
},
{
name: "handball",
photo_url: "https://blog.scorenco.com/wp-content/uploads/2014/11/Handball.jpg"
},
{
name: "rugby",
photo_url: "http://business.lesechos.fr/images/2015/09/09/202649_du-rugby-pour-susciter-l-engagement-des-salaries-d-alstom-transport-web-tete-021293635085.jpg"
},
{
name: "golf",
photo_url: "http://www.viagolf.fr/wp-content/uploads/2016/03/aaa.jpg"
},
{
name: "sexe",
photo_url: "http://genevievecoteauteure.com/boutique/image/catalog/Image%20G.C/Fotolia_88901350_Subscription_Monthly_M.jpg"
},
{
name: "woman football",
photo_url: "http://imgview.info/download/20151012/women-adriana-lima-candice-swanepoel-lily-aldridge-behati-prinsloo-group-of-women-american-football-doutzen-kroes-helmet-sports-2560x1600.jpg"
},
{
name: "Lacrosse",
photo_url: "http://www.thehill.org/Customized/Uploads/ByDate/2015/July_2015/July_21st_2015/Boys%20Lax72824.JPG"
},
{
name: "Hockey",
photo_url: "http://www.lareleve.qc.ca/media/photos/unis/2016/02/18/2016-02-18-06-45-06-hockey.jpg"
},
{
name: "Polo",
photo_url: "http://karenine.com/wp-content/uploads/2013/12/polo-sport.jpg"
},
{
name: "tir a l'arc",
photo_url: "http://www.valjoly.com/wp-content/uploads/2013/07/tirAlArc-slide2.jpg"
}
]
sports.each { |params| Sport.create(params) }
User.destroy_all
user_attributes = [
{
first_name: "Jonathan",
last_name: "Bobo",
email: "jojolapin@gmail.com",
password: "blabla",
gender: "male",
birthday: Date.today - 7281,
description: "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.",
status: "available"
},
{
first_name: "Paul",
last_name: "Pot",
email: "potpot@gmail.com",
password: "blabla",
gender: "male",
birthday: Date.today - 7389,
status: "available",
description: "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.",
photo_url: "http://www.elevagedelapin.fr/wp-content/uploads/2014/12/lapin-216311.jpg"
},
{
first_name: "Lea",
last_name: "Connor",
email: "leaconnor@gmail.com",
password: "blabla",
gender: "female",
birthday: Date.today - 7389,
status: "available",
description: "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.",
photo_url: "http://www.elevagedelapin.fr/wp-content/uploads/2014/12/lapin-216311.jpg"
},
{
first_name: "Emma",
last_name: "Dupont",
email: "emmadupont@gmail.com",
password: "blabla",
gender: "female",
birthday: Date.today - 7389,
status: "available",
description: "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.",
photo_url: "http://www.elevagedelapin.fr/wp-content/uploads/2014/12/lapin-216311.jpg"
},
{
first_name: "Jacques",
last_name: "Bordeaux",
email: "jacquesbordeaux@gmail.com",
password: "blabla",
gender: "male",
birthday: Date.today - 7389,
status: "available",
description: "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.",
photo_url: "https://avatars.githubusercontent.com/u/20277922?v=3"
},
{
first_name: "Paulo",
last_name: "Robert",
email: "paulorobert@gmail.com",
password: "blabla",
gender: "male",
birthday: Date.today - 7389,
status: "available",
description: "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.",
photo_url: "http://www.elevagedelapin.fr/wp-content/uploads/2014/12/lapin-216311.jpg"
},
{
first_name: "Loan",
last_name: "Robert",
email: "loanrobert@gmail.com",
password: "blabla",
gender: "male",
birthday: Date.today - 7389,
status: "available",
description: "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.",
photo_url: "https://avatars.githubusercontent.com/u/20277922?v=3"
},
{
first_name: "Poulou",
last_name: "Boulobou",
email: "bouloubo@gmail.com",
password: "blabla",
gender: "female",
birthday: Date.today - 11526,
description: "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.",
status: "available"
},
{
first_name: "Claire",
last_name: "Bye",
email: "clairye@gmail.com",
password: "blabla",
gender: "male",
birthday: Date.today - 2018,
description: "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.",
status: "available"
},
{
first_name: "John",
last_name: "bobo",
email: "johni@gmail.com",
password: "blabla",
gender: "male",
birthday: Date.today - 6378,
description: "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.",
status: "available"
},
{
first_name: "Johanna",
last_name: "bololo",
email: "lolo@gmail.com",
password: "blabla",
gender: "female",
birthday: Date.today - 156,
description: "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.",
status: "available"
},
]
user_attributes.each { |params| User.create(params) }
Place.destroy_all
places_attributes = [
{
name: "Racing Club de France",
address: "154 Rue de Saussure, 75017, Paris, France",
description: "Very fancy dear Sir"
},
{
name: "Polo de Paris",
address: " Route des Moulins, 75116 Paris, France",
description: "Ever more fancy"
}
]
places_attributes.each { |params| Place.create(params) }
Event.destroy_all
events_attributes = [
{
name: "tournoi amateur",
required_level: "2",
required_material: "true",
status: "open",
sport: Sport.all.sample,
date: Date.tomorrow,
time: Time.now,
user: User.all.sample,
address: "Pessac, France",
number_of_players: 4
},
{
name: "Sport co",
required_level: "3",
required_material: "true",
status: "open",
sport: Sport.all.sample,
date: Date.tomorrow,
time: Time.now,
user: User.all.sample,
address: "Bordeaux, France",
number_of_players: 4
},
{
name: "MyEvent#1",
required_level: "1",
required_material: "true",
status: "waiting list",
sport: Sport.all.sample,
date: Date.tomorrow,
time: Time.now,
user: User.all.sample,
address: "Lille, France",
number_of_players: 4
},
{
name: "MyEvent#2",
required_level: "1",
required_material: "true",
status: "waiting list",
sport: Sport.all.sample,
date: Date.tomorrow,
time: Time.now,
user: User.all.sample,
address: "Toulouse, France",
number_of_players: 4
},
{
name: "MyEvent#3",
required_level: "1",
required_material: "true",
status: "waiting list",
sport: Sport.all.sample,
date: Date.tomorrow,
time: Time.now,
user: User.all.sample,
address: "Toulon, France",
number_of_players: 4
},
{
name: "MyEvent#4",
required_level: "1",
required_material: "true",
status: "waiting list",
sport: Sport.all.sample,
date: Date.tomorrow,
time: Time.now,
user: User.all.sample,
address: "Nantes, France",
number_of_players: 4
},
{
name: "MyEvent#5",
required_level: "1",
required_material: "true",
status: "waiting list",
sport: Sport.all.sample,
date: Date.tomorrow,
time: Time.now,
user: User.all.sample,
address: "Brest, France",
number_of_players: 4
},
{
name: "MyEvent#6",
required_level: "1",
required_material: "true",
status: "waiting list",
sport: Sport.all.sample,
date: Date.tomorrow,
time: Time.now,
user: User.all.sample,
address: "Strasbourg, France",
number_of_players: 4
},
{
name: "MyEvent#7",
required_level: "1",
required_material: "true",
status: "waiting list",
sport: Sport.all.sample,
date: Date.tomorrow,
time: Time.now,
user: User.all.sample,
address: "Toulouse, France",
number_of_players: 4
},
{
name: "Qui est partant?",
required_level: "2",
required_material: "true",
status: "open",
sport: Sport.all.sample,
date: Date.tomorrow,
time: Time.now,
user: User.all.sample,
address: "101 Allée quai des Chartrons, Bordeaux, France",
number_of_players: 4
},
{
name: "Allez on se chauffe !",
required_level: "4",
required_material: "true",
status: "waiting list",
sport: Sport.all.sample,
date: Date.tomorrow,
time: Time.now,
user: User.all.sample,
address: "17 Place de la bourse, Bordeaux, France",
number_of_players: 4
}
]
events_attributes.each { |params| Event.create(params) }
Message.destroy_all
messages_attributes = []
Event.all.each do |event|
messages_attributes << {
content: "Bienvenue sur le tchat !",
event: event,
participation: Participation.new(status: "orgaiser", user: User.all.sample, event: event)
}
end
messages_attributes.each { |params| Message.create(params) }
|
class Comment < ActiveRecord::Base
belongs_to :post
validates :user, presence: true
validates :text, presence: true
end
|
require 'rails_helper'
describe SendNotifications do
it '.pending_reviews preperly calls correct mailer' do
create :card
create :another_user_card
mailer_class = class_double('NotificationsMailer').as_stubbed_const
message = double('ActionMailer::MessageDelivery')
expect(mailer_class).to receive(:pending).and_return(message).twice
expect(message).to receive(:deliver_now).twice
SendNotifications.pending_reviews
end
end
|
class ApprovalController < SecureController
get '/:uuid' do |uuid|
status 202
approval = Approval.find_by_uuid(uuid)
if approval.nil?
request_halt("Unable to find approval link for uuid: #{uuid}", 404)
else
approval.update!(accepted: true)
logger.info("Approved: #{uuid}")
end
{ status: 'ok' }.to_json
end
end
|
class ContentSourcesController < ApplicationController
before_action :set_content_source, only: [:show, :edit, :update, :destroy]
# GET /content_sources
# GET /content_sources.json
def index
@content_sources = ContentSource.all
end
# GET /content_sources/1
# GET /content_sources/1.json
def show
end
# GET /content_sources/new
def new
@content_source = ContentSource.new
end
# GET /content_sources/1/edit
def edit
end
# POST /content_sources
# POST /content_sources.json
def create
@content_source = ContentSource.new(content_source_params)
respond_to do |format|
if @content_source.save
format.html { redirect_to @content_source, notice: 'Content source was successfully created.' }
format.json { render :show, status: :created, location: @content_source }
else
format.html { render :new }
format.json { render json: @content_source.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /content_sources/1
# PATCH/PUT /content_sources/1.json
def update
respond_to do |format|
if @content_source.update(content_source_params)
format.html { redirect_to @content_source, notice: 'Content source was successfully updated.' }
format.json { render :show, status: :ok, location: @content_source }
else
format.html { render :edit }
format.json { render json: @content_source.errors, status: :unprocessable_entity }
end
end
end
# DELETE /content_sources/1
# DELETE /content_sources/1.json
def destroy
@content_source.destroy
respond_to do |format|
format.html { redirect_to content_sources_url, notice: 'Content source was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_content_source
@content_source = ContentSource.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def content_source_params
params.require(:content_source).permit(:title, :description, :link, :version)
end
end
|
require 'skeptick/sugar/compose'
require 'skeptick/sugar/format'
require 'skeptick/sugar/draw'
module Skeptick
module RoundedCornersImage
def rounded_corners_image(*args, &blk)
opts = args.last.is_a?(Hash) ? args.pop : {}
radius = opts[:radius] || 15
size = opts[:size]
width = opts[:width]
height = opts[:height]
if size
width, height = size.split('x').map(&:to_i)
end
border = if width && height
"roundrectangle 1,1 #{width},#{height} #{radius},#{radius}"
else
Convert.new(self, *args, to: 'info:') do
format "roundrectangle 1,1 %[fx:w], %[fx:h] #{radius},#{radius}"
end.run.strip
end
compose(:dstin, *args) do
convert(&blk) if block_given?
convert do
set '+clone'
set :draw, border
end
end
end
end
class DslContext
include RoundedCornersImage
end
include RoundedCornersImage
end
|
# frozen_string_literal: true
require 'stannum/contracts/parameters/arguments_contract'
require 'support/examples/constraint_examples'
require 'support/examples/contract_examples'
RSpec.describe Stannum::Contracts::Parameters::ArgumentsContract do
include Spec::Support::Examples::ConstraintExamples
include Spec::Support::Examples::ContractExamples
shared_context 'when the contract has many argument constraints' do
let(:constraints) do
[
{
constraint: Stannum::Constraints::Presence.new
},
{
constraint: Stannum::Constraints::Presence.new,
options: { type: :index, key: 'value' }
},
{
constraint: Stannum::Constraints::Type.new(Integer),
options: { type: :index, ichi: 1, ni: 2, san: 3 }
}
]
end
let(:definitions) do
constraints.map.with_index do |definition, index|
options = definition.fetch(:options, {})
be_a_constraint_definition(
constraint: definition[:constraint].with_options(**options),
contract: contract,
options: {
default: false,
property: index,
property_type: :index,
sanity: false
}
.merge(options)
)
end
end
before(:example) do
constraints.each.with_index do |definition, index|
contract.add_argument_constraint(
index,
definition[:constraint],
**definition.fetch(:options, {})
)
end
end
end
shared_context 'when the contract has argument constraints with defaults' do
let(:constraints) do
[
{
constraint: Stannum::Constraints::Presence.new
},
{
constraint: Stannum::Constraints::Type.new(String),
options: { default: true, type: :index, key: 'value' }
},
{
constraint: Stannum::Constraints::Type.new(Integer),
options: { default: true, type: :index, ichi: 1, ni: 2, san: 3 }
}
]
end
let(:definitions) do
constraints.map.with_index do |definition, index|
options = definition.fetch(:options, {})
constraint_options = options.dup.tap { |hsh| hsh.delete(:default) }
constraint =
definition[:constraint].with_options(**constraint_options)
be_a_constraint_definition(
constraint: constraint,
contract: contract,
options: {
default: false,
property: index,
property_type: :index,
sanity: false
}
.merge(options)
)
end
end
before(:example) do
constraints.each.with_index do |definition, index|
contract.add_argument_constraint(
index,
definition[:constraint],
**definition.fetch(:options, {})
)
end
end
end
shared_context 'when the contract has a variadic arguments constraint' do
let(:receiver) do
Stannum::Constraints::Types::ArrayType.new(item_type: String)
end
let(:receiver_definition) do
be_a_constraint(Stannum::Constraints::Types::ArrayType).and(
satisfy do |constraint|
constraint.item_type.is_a?(Stannum::Constraints::Type) &&
constraint.item_type.expected_type == String
end
)
end
before(:example) { contract.set_variadic_constraint(receiver) }
end
subject(:contract) do
described_class.new(**constructor_options)
end
let(:constructor_options) { {} }
let(:expected_options) { { allow_extra_items: false } }
describe '::UNDEFINED' do
include_examples 'should define immutable constant', :UNDEFINED
end
describe '.new' do
it 'should define the constructor' do
expect(described_class)
.to be_constructible
.with(0).arguments
.and_any_keywords
end
end
include_examples 'should implement the Constraint interface'
include_examples 'should implement the Constraint methods'
include_examples 'should implement the Contract methods'
describe '#add_argument_constraint' do
let(:definition) { contract.each_constraint.to_a.last }
it 'should define the method' do
expect(contract)
.to respond_to(:add_argument_constraint)
.with(2).arguments
.and_keywords(:default, :sanity)
.and_any_keywords
end
it { expect(contract.add_argument_constraint(0, String)).to be contract }
describe 'with default: false' do
let(:expected_constraint) do
be_a(Stannum::Constraints::Type).and(
have_attributes(expected_type: String)
)
end
it 'should add the constraint to the contract' do
expect { contract.add_argument_constraint(nil, String, default: false) }
.to change { contract.each_constraint.count }
.by(1)
end
it 'should store the contract' do # rubocop:disable RSpec/ExampleLength
contract.add_argument_constraint(nil, String, default: false)
expect(definition).to be_a_constraint_definition(
constraint: expected_constraint,
contract: contract,
options: {
default: false,
property: 0,
property_type: :index,
sanity: false
}
)
end
end
describe 'with default: true' do
let(:expected_constraint) do
be_a(Stannum::Constraints::Type).and(
have_attributes(expected_type: String)
)
end
it 'should add the constraint to the contract' do
expect { contract.add_argument_constraint(nil, String, default: true) }
.to change { contract.each_constraint.count }
.by(1)
end
it 'should store the contract' do # rubocop:disable RSpec/ExampleLength
contract.add_argument_constraint(nil, String, default: true)
expect(definition).to be_a_constraint_definition(
constraint: expected_constraint,
contract: contract,
options: {
default: true,
property: 0,
property_type: :index,
sanity: false
}
)
end
end
describe 'with index: nil' do
let(:expected_constraint) do
be_a(Stannum::Constraints::Type).and(
have_attributes(expected_type: String)
)
end
it 'should add the constraint to the contract' do
expect { contract.add_argument_constraint(nil, String) }
.to change { contract.each_constraint.count }
.by(1)
end
it 'should store the contract' do # rubocop:disable RSpec/ExampleLength
contract.add_argument_constraint(nil, String)
expect(definition).to be_a_constraint_definition(
constraint: expected_constraint,
contract: contract,
options: {
default: false,
property: 0,
property_type: :index,
sanity: false
}
)
end
wrap_context 'when the contract has many argument constraints' do
it 'should store the contract' do # rubocop:disable RSpec/ExampleLength
contract.add_argument_constraint(nil, String)
expect(definition).to be_a_constraint_definition(
constraint: expected_constraint,
contract: contract,
options: {
default: false,
property: constraints.size,
property_type: :index,
sanity: false
}
)
end
end
end
describe 'with index: an object' do
let(:index) { Object.new.freeze }
let(:error_message) { "invalid property name #{index.inspect}" }
it 'should raise an error' do
expect do
contract.add_argument_constraint(index, String)
end
.to raise_error ArgumentError, error_message
end
end
describe 'with index: an integer' do
let(:expected_constraint) do
be_a(Stannum::Constraints::Type).and(
have_attributes(expected_type: String)
)
end
it 'should add the constraint to the contract' do
expect { contract.add_argument_constraint(3, String) }
.to change { contract.each_constraint.count }
.by(1)
end
it 'should store the contract' do # rubocop:disable RSpec/ExampleLength
contract.add_argument_constraint(3, String)
expect(definition).to be_a_constraint_definition(
constraint: expected_constraint,
contract: contract,
options: {
default: false,
property: 3,
property_type: :index,
sanity: false
}
)
end
end
describe 'with type: nil' do
let(:error_message) do
'type must be a Class or Module or a constraint'
end
it 'should raise an error' do
expect { contract.add_argument_constraint(nil, nil) }
.to raise_error ArgumentError, error_message
end
end
describe 'with type: an object' do
let(:error_message) do
'type must be a Class or Module or a constraint'
end
it 'should raise an error' do
expect { contract.add_argument_constraint(nil, Object.new.freeze) }
.to raise_error ArgumentError, error_message
end
end
describe 'with type: a class' do
let(:expected_constraint) do
be_a(Stannum::Constraints::Type).and(
have_attributes(expected_type: Symbol)
)
end
it 'should add the constraint to the contract' do
expect { contract.add_argument_constraint(nil, Symbol) }
.to change { contract.each_constraint.count }
.by(1)
end
it 'should store the contract' do # rubocop:disable RSpec/ExampleLength
contract.add_argument_constraint(nil, Symbol)
expect(definition).to be_a_constraint_definition(
constraint: expected_constraint,
contract: contract,
options: {
default: false,
property: 0,
property_type: :index,
sanity: false
}
)
end
end
describe 'with type: a constraint' do
let(:constraint) { Stannum::Constraints::Type.new(String) }
it 'should add the constraint to the contract' do
expect { contract.add_argument_constraint(nil, constraint) }
.to change { contract.each_constraint.count }
.by(1)
end
it 'should store the contract' do # rubocop:disable RSpec/ExampleLength
contract.add_argument_constraint(nil, constraint)
expect(definition).to be_a_constraint_definition(
constraint: constraint,
contract: contract,
options: {
default: false,
property: 0,
property_type: :index,
sanity: false
}
)
end
end
describe 'with options' do
let(:options) { { key: 'value' } }
let(:expected_constraint) do
be_a(Stannum::Constraints::Type).and(
have_attributes(expected_type: Symbol)
)
end
it 'should add the constraint to the contract' do
expect { contract.add_argument_constraint(nil, Symbol, **options) }
.to change { contract.each_constraint.count }
.by(1)
end
it 'should store the contract' do # rubocop:disable RSpec/ExampleLength
contract.add_argument_constraint(nil, Symbol, **options)
expect(definition).to be_a_constraint_definition(
constraint: expected_constraint,
contract: contract,
options: {
default: false,
property: 0,
property_type: :index,
sanity: false,
**options
}
)
end
end
end
describe '#add_errors_for' do
describe 'with value: UNDEFINED' do
let(:value) { described_class::UNDEFINED }
let(:errors) { Stannum::Errors.new }
let(:options) { {} }
let(:constraint) { Stannum::Constraints::Presence.new }
let(:definition) do
Stannum::Contracts::Definition.new(
constraint: constraint,
contract: contract,
options: options
)
end
it 'should add the errors from the constraint' do
expect(contract.send(:add_errors_for, definition, value, errors))
.to be == constraint.errors_for(nil)
end
it 'should delegate to the constraint with value: nil' do
allow(constraint).to receive(:errors_for)
contract.send(:add_errors_for, definition, value, errors)
expect(constraint)
.to have_received(:errors_for)
.with(nil, errors: errors)
end
end
end
describe '#add_negated_errors_for' do
describe 'with value: UNDEFINED' do
let(:value) { described_class::UNDEFINED }
let(:errors) { Stannum::Errors.new }
let(:options) { {} }
let(:constraint) { Stannum::Constraints::Presence.new }
let(:definition) do
Stannum::Contracts::Definition.new(
constraint: constraint,
contract: contract,
options: options
)
end
it 'should add the errors from the constraint' do
expect(
contract.send(:add_negated_errors_for, definition, value, errors)
)
.to be == constraint.negated_errors_for(nil)
end
it 'should delegate to the constraint with value: nil' do
allow(constraint).to receive(:negated_errors_for)
contract.send(:add_negated_errors_for, definition, value, errors)
expect(constraint)
.to have_received(:negated_errors_for)
.with(nil, errors: errors)
end
end
end
describe '#allow_extra_items?' do
include_examples 'should have predicate', :allow_extra_items?, false
wrap_context 'when the contract has a variadic arguments constraint' do
it { expect(contract.allow_extra_items?).to be true }
end
end
describe '#each_constraint' do
let(:items_count) { 0 }
let(:receiver_definition) do
be_a_constraint(Stannum::Constraints::Tuples::ExtraItems)
.and(satisfy { |constraint| constraint.expected_count == items_count })
end
let(:delegator_definition) do
be_a_constraint(Stannum::Constraints::Delegator).and(
satisfy do |constraint|
receiver_definition.matches?(constraint.receiver)
end
)
end
let(:builtin_definitions) do
[
be_a_constraint_definition(
constraint: be_a_constraint(Stannum::Constraints::Signatures::Tuple),
contract: contract,
options: { property: nil, sanity: true }
),
be_a_constraint_definition(
constraint: delegator_definition,
contract: contract,
options: { property: nil, sanity: false }
)
]
end
let(:expected) { builtin_definitions }
it { expect(contract).to respond_to(:each_constraint).with(0).arguments }
it { expect(contract.each_constraint).to be_a Enumerator }
it { expect(contract.each_constraint.count).to be 2 }
it 'should yield each definition' do
expect { |block| contract.each_constraint(&block) }
.to yield_successive_args(*expected)
end
# rubocop:disable RSpec/RepeatedExampleGroupBody
wrap_context 'when the contract has many argument constraints' do
let(:items_count) { definitions.count }
let(:expected) { builtin_definitions + definitions }
it { expect(contract.each_constraint.count).to be(2 + constraints.size) }
it 'should yield each definition' do
expect { |block| contract.each_constraint(&block) }
.to yield_successive_args(*expected)
end
wrap_context 'when the contract has a variadic arguments constraint' do
it 'should yield each definition' do
expect { |block| contract.each_constraint(&block) }
.to yield_successive_args(*expected)
end
end
end
wrap_context 'when the contract has argument constraints with defaults' do
let(:items_count) { definitions.count }
let(:expected) { builtin_definitions + definitions }
it { expect(contract.each_constraint.count).to be(2 + constraints.size) }
it 'should yield each definition' do
expect { |block| contract.each_constraint(&block) }
.to yield_successive_args(*expected)
end
wrap_context 'when the contract has a variadic arguments constraint' do
it 'should yield each definition' do
expect { |block| contract.each_constraint(&block) }
.to yield_successive_args(*expected)
end
end
end
# rubocop:enable RSpec/RepeatedExampleGroupBody
wrap_context 'when the contract has a variadic arguments constraint' do
it 'should yield each definition' do
expect { |block| contract.each_constraint(&block) }
.to yield_successive_args(*expected)
end
end
end
describe '#each_pair' do
let(:actual) { %w[ichi ni san] }
let(:items_count) { 0 }
let(:receiver_definition) do
be_a_constraint(Stannum::Constraints::Tuples::ExtraItems)
.and(satisfy { |constraint| constraint.expected_count == items_count })
end
let(:delegator_definition) do
be_a_constraint(Stannum::Constraints::Delegator).and(
satisfy do |constraint|
receiver_definition.matches?(constraint.receiver)
end
)
end
let(:builtin_definitions) do
[
be_a_constraint_definition(
constraint: be_a_constraint(Stannum::Constraints::Signatures::Tuple),
contract: contract,
options: { property: nil, sanity: true }
),
be_a_constraint_definition(
constraint: delegator_definition,
contract: contract,
options: { property: nil, sanity: false }
)
]
end
let(:expected) do
builtin_definitions.zip(Array.new(builtin_definitions.size, actual))
end
it { expect(contract).to respond_to(:each_pair).with(1).argument }
it { expect(contract.each_pair(actual)).to be_a Enumerator }
it { expect(contract.each_pair(actual).count).to be 2 + items_count }
it 'should yield each definition and the mapped property' do
expect { |block| contract.each_pair(actual, &block) }
.to yield_successive_args(*expected)
end
wrap_context 'when the contract has many argument constraints' do
let(:items_count) { definitions.count }
let(:expected) do
builtin_definitions.zip(Array.new(builtin_definitions.size, actual)) +
definitions.zip(actual)
end
it { expect(contract.each_pair(actual).count).to be(expected.size) }
it 'should yield each definition and the mapped property' do
expect { |block| contract.each_pair(actual, &block) }
.to yield_successive_args(*expected)
end
wrap_context 'when the contract has a variadic arguments constraint' do
it 'should yield each definition and the mapped property' do
expect { |block| contract.each_pair(actual, &block) }
.to yield_successive_args(*expected)
end
end
end
wrap_context 'when the contract has argument constraints with defaults' do
let(:items_count) { definitions.count }
describe 'with an empty array' do
let(:actual) { [] }
let(:expected) do
builtin_definitions.zip(Array.new(builtin_definitions.size, actual)) +
definitions.zip(Array.new(3, described_class::UNDEFINED))
end
it { expect(contract.each_pair(actual).count).to be(expected.size) }
it 'should yield each definition and the mapped property' do
expect { |block| contract.each_pair(actual, &block) }
.to yield_successive_args(*expected)
end
wrap_context 'when the contract has a variadic arguments constraint' do
it 'should yield each definition and the mapped property' do
expect { |block| contract.each_pair(actual, &block) }
.to yield_successive_args(*expected)
end
end
end
describe 'with an array with required values' do
let(:actual) { %w[ichi] }
let(:expected) do
builtin_definitions.zip(Array.new(builtin_definitions.size, actual)) +
definitions.zip(
[*actual, described_class::UNDEFINED, described_class::UNDEFINED]
)
end
it { expect(contract.each_pair(actual).count).to be(expected.size) }
it 'should yield each definition and the mapped property' do
expect { |block| contract.each_pair(actual, &block) }
.to yield_successive_args(*expected)
end
wrap_context 'when the contract has a variadic arguments constraint' do
it 'should yield each definition and the mapped property' do
expect { |block| contract.each_pair(actual, &block) }
.to yield_successive_args(*expected)
end
end
end
describe 'with an array with required and optional values' do
let(:actual) { %w[ichi ni san] }
let(:expected) do
builtin_definitions.zip(Array.new(builtin_definitions.size, actual)) +
definitions.zip(actual)
end
it { expect(contract.each_pair(actual).count).to be(expected.size) }
it 'should yield each definition and the mapped property' do
expect { |block| contract.each_pair(actual, &block) }
.to yield_successive_args(*expected)
end
wrap_context 'when the contract has a variadic arguments constraint' do
it 'should yield each definition and the mapped property' do
expect { |block| contract.each_pair(actual, &block) }
.to yield_successive_args(*expected)
end
end
end
end
wrap_context 'when the contract has a variadic arguments constraint' do
it 'should yield each definition and the mapped property' do
expect { |block| contract.each_pair(actual, &block) }
.to yield_successive_args(*expected)
end
end
end
describe '#map_value' do
let(:actual) { Struct.new(:name).new('Alan Bradley') }
it { expect(contract.send(:map_value, actual)).to be actual }
it 'should return the property' do
expect(contract.send(:map_value, actual, property: :name))
.to be == actual.name
end
describe 'with property type: :index' do
let(:actual) { %w[ichi ni san] }
let(:index) { 1 }
let(:options) { { property: index, property_type: :index } }
context 'when the index is less than the array size' do
let(:index) { 2 }
it 'should return the indexed value' do
expect(contract.send(:map_value, actual, **options))
.to be == actual[index]
end
end
context 'when the index is equal to the array size' do
let(:index) { 3 }
it 'should return the indexed value' do
expect(contract.send(:map_value, actual, **options))
.to be == described_class::UNDEFINED
end
end
context 'when the index is greater than the array size' do
let(:index) { 4 }
it 'should return the indexed value' do
expect(contract.send(:map_value, actual, **options))
.to be == described_class::UNDEFINED
end
end
end
end
describe '#match' do
wrap_context 'when the contract has argument constraints with defaults' do
let(:result) { contract.match(actual).first }
let(:errors) { contract.match(actual).last }
describe 'with an empty arguments array' do
let(:actual) { [] }
it { expect(result).to be false }
it { expect(errors[0]).not_to be_empty }
end
describe 'with an arguments array with required values' do
let(:actual) { [Object.new.freeze] }
it { expect(result).to be true }
end
describe 'with an arguments array with required and optional values' do
let(:actual) { [Object.new.freeze, '', 0] }
it { expect(result).to be true }
end
describe 'with an arguments array with explicit nil values' do
let(:actual) { [Object.new.freeze, nil, nil] }
it { expect(result).to be false }
it { expect(errors[1]).not_to be_empty }
it { expect(errors[2]).not_to be_empty }
end
end
end
describe '#match_constraint' do
describe 'with value: UNDEFINED' do
let(:value) { described_class::UNDEFINED }
let(:options) { {} }
let(:constraint) { Stannum::Constraints::Presence.new }
let(:definition) do
Stannum::Contracts::Definition.new(
constraint: constraint,
options: options
)
end
context 'when the constraint has default: false' do
it 'should match nil to the constraint' do
expect(contract.send(:match_constraint, definition, value))
.to be == constraint.matches?(nil)
end
it 'should delegate to the constraint' do
allow(constraint).to receive(:matches?)
contract.send(:match_constraint, definition, value)
expect(constraint).to have_received(:matches?).with(nil)
end
end
context 'when the constraint has default: true' do
let(:options) { { default: true } }
it 'should return true' do
expect(contract.send(:match_constraint, definition, value))
.to be true
end
it 'should not delegate to the constraint' do
allow(constraint).to receive(:matches?)
contract.send(:match_constraint, definition, value)
expect(constraint).not_to have_received(:matches?)
end
end
end
end
describe '#match_negated_constraint' do
describe 'with value: UNDEFINED' do
let(:value) { described_class::UNDEFINED }
let(:options) { {} }
let(:constraint) { Stannum::Constraints::Presence.new }
let(:definition) do
Stannum::Contracts::Definition.new(
constraint: constraint,
options: options
)
end
context 'when the constraint has default: false' do
it 'should match nil to the constraint' do
expect(contract.send(:match_negated_constraint, definition, value))
.to be == constraint.does_not_match?(nil)
end
it 'should delegate to the constraint' do
allow(constraint).to receive(:does_not_match?)
contract.send(:match_negated_constraint, definition, value)
expect(constraint).to have_received(:does_not_match?).with(nil)
end
end
context 'when the constraint has default: true' do
let(:options) { { default: true } }
it 'should return true' do
expect(contract.send(:match_negated_constraint, definition, value))
.to be false
end
it 'should not delegate to the constraint' do
allow(constraint).to receive(:does_not_match?)
contract.send(:match_negated_constraint, definition, value)
expect(constraint).not_to have_received(:does_not_match?)
end
end
end
end
describe '#negated_match' do
wrap_context 'when the contract has argument constraints with defaults' do
let(:result) { contract.negated_match(actual).first }
let(:errors) { contract.negated_match(actual).last }
describe 'with an empty arguments array' do
let(:actual) { [] }
it { expect(result).to be false }
it { expect(errors[0]).to be_empty }
it { expect(errors[1]).not_to be_empty }
it { expect(errors[2]).not_to be_empty }
end
describe 'with an arguments array with required values' do
let(:actual) { [Object.new.freeze] }
it { expect(result).to be false }
it { expect(errors[0]).not_to be_empty }
it { expect(errors[1]).not_to be_empty }
it { expect(errors[2]).not_to be_empty }
end
describe 'with an arguments array with required and optional values' do
let(:actual) { [Object.new.freeze, '', 0] }
it { expect(result).to be false }
it { expect(errors[0]).not_to be_empty }
it { expect(errors[1]).not_to be_empty }
it { expect(errors[2]).not_to be_empty }
end
end
end
describe '#set_variadic_constraint' do
let(:definition) { contract.each_constraint.to_a.last }
let(:receiver) { contract.send(:variadic_constraint).receiver }
it 'should define the method' do
expect(contract).to respond_to(:set_variadic_constraint).with(1).argument
end
it 'should return the contract' do
expect(contract.set_variadic_constraint Stannum::Constraint.new)
.to be contract
end
describe 'with nil' do
let(:error_message) do
'receiver must be a Stannum::Constraints::Base'
end
it 'should raise an exception' do
expect { contract.set_variadic_constraint nil }
.to raise_error ArgumentError, error_message
end
end
describe 'with an object' do
let(:error_message) do
'receiver must be a Stannum::Constraints::Base'
end
it 'should raise an exception' do
expect { contract.set_variadic_constraint Object.new.freeze }
.to raise_error ArgumentError, error_message
end
end
describe 'with a class' do
let(:error_message) do
'receiver must be a Stannum::Constraints::Base'
end
it 'should raise an exception' do
expect { contract.set_variadic_constraint String }
.to raise_error ArgumentError, error_message
end
end
describe 'with a constraint' do
let(:constraint) { Stannum::Constraint.new(type: 'spec.type') }
it 'should update the variadic constraint', :aggregate_failures do
contract.set_variadic_constraint(constraint)
expect(receiver).to be_a Stannum::Constraint
expect(receiver.options).to be == constraint.options
end
end
wrap_context 'when the contract has a variadic arguments constraint' do
let(:constraint) { Stannum::Constraint.new }
let(:error_message) { 'variadic arguments constraint is already set' }
it 'should raise an error' do
expect { contract.set_variadic_constraint constraint }
.to raise_error RuntimeError, error_message
end
end
end
describe '#set_variadic_item_constraint' do
let(:definition) { contract.send(:variadic_definition) }
let(:receiver) { contract.send(:variadic_constraint).receiver }
it 'should define the method' do
expect(contract)
.to respond_to(:set_variadic_item_constraint)
.with(1).argument
.and_keywords(:as)
end
it 'should return the contract' do
expect(contract.set_variadic_item_constraint Stannum::Constraint.new)
.to be contract
end
describe 'with nil' do
let(:error_message) do
'item type must be a Class or Module or a constraint'
end
it 'should raise an exception' do
expect { contract.set_variadic_item_constraint nil }
.to raise_error ArgumentError, error_message
end
end
describe 'with an object' do
let(:error_message) do
'item type must be a Class or Module or a constraint'
end
it 'should raise an exception' do
expect { contract.set_variadic_item_constraint Object.new.freeze }
.to raise_error ArgumentError, error_message
end
end
describe 'with a class' do
let(:type) { String }
it 'should update the variadic constraint', :aggregate_failures do
contract.set_variadic_item_constraint(type)
expect(receiver).to be_a Stannum::Constraints::Types::ArrayType
expect(receiver.item_type).to be_a Stannum::Constraints::Type
expect(receiver.item_type.expected_type).to be type
end
describe 'with as: a value' do
it 'should update the variadic constraint', :aggregate_failures do
contract.set_variadic_item_constraint(type, as: :splatted)
expect(receiver).to be_a Stannum::Constraints::Types::ArrayType
expect(receiver.item_type).to be_a Stannum::Constraints::Type
expect(receiver.item_type.expected_type).to be type
end
it 'should update the property name' do
expect { contract.set_variadic_item_constraint(type, as: :splatted) }
.to change(definition, :property_name)
.to be :splatted
end
end
end
describe 'with a constraint' do
let(:constraint) { Stannum::Constraint.new(type: 'spec.type') }
it 'should update the variadic constraint', :aggregate_failures do
contract.set_variadic_item_constraint(constraint)
expect(receiver).to be_a Stannum::Constraints::Types::ArrayType
expect(receiver.item_type).to be_a Stannum::Constraint
expect(receiver.item_type.options).to be == constraint.options
end
describe 'with as: a value' do
it 'should update the variadic constraint', :aggregate_failures do
contract.set_variadic_item_constraint(constraint, as: :splatted)
expect(receiver).to be_a Stannum::Constraints::Types::ArrayType
expect(receiver.item_type).to be_a Stannum::Constraint
expect(receiver.item_type.options).to be == constraint.options
end
it 'should update the property name' do
expect do
contract.set_variadic_item_constraint(constraint, as: :splatted)
end
.to change(definition, :property_name)
.to be :splatted
end
end
end
wrap_context 'when the contract has a variadic arguments constraint' do
let(:constraint) { Stannum::Constraint.new }
let(:error_message) { 'variadic arguments constraint is already set' }
it 'should raise an error' do
expect { contract.set_variadic_item_constraint constraint }
.to raise_error RuntimeError, error_message
end
end
end
end
|
# frozen_string_literal: true
require 'cloudflare_clearance/exceptions'
require "cloudflare_clearance/cookie_set"
require 'cloudflare_clearance/drivers/driver'
module CloudflareClearance
class Selenium < Driver
DEFAULT_BROWSER = :firefox
#DEFAULT_OPTS = ::Selenium::WebDriver::Firefox::Options.new(
#args: ['-headless']
#)
def initialize(selenium_webdriver: (::Selenium::WebDriver.for DEFAULT_BROWSER, options: default_options))
require "selenium-webdriver"
@driver = selenium_webdriver
end
def get_clearance(url, retries: 5, seconds_wait_retry: 6)
@driver.get(url)
cookieset = wait_for_cookies(retries, seconds_wait_retry)
ClearanceData.new(user_agent: user_agent, cookieset: cookieset)
end
def self.available?
require "selenium-webdriver"
true
rescue LoadError
false
end
def self.deprecated?
false
end
private
def default_options
::Selenium::WebDriver::Firefox::Options.new(
args: ['-headless']
)
end
def user_agent
@driver.execute_script("return navigator.userAgent")
end
def wait_for_cookies(retries, seconds_wait_retry)
CookieSet.from_cookiehash(cookies)
rescue CookieError => e
if (retries -= 1) >= 0
sleep seconds_wait_retry
retry
else
raise ClearanceError, "Unable to obtain clearance. #{e.class.name} Reason: #{e.message}"
end
end
def cookies
@driver.manage.all_cookies
end
end
end
|
class Gist < ApplicationRecord
belongs_to :question
belongs_to :user
validates :url, presence: true
def hash
url.split('/')[-1]
end
end
|
require_relative '../../klass/entity'
require 'test/unit'
class EntityTest < Test::Unit::TestCase
def setup
@id = 1, @table = "MyTable"
@entity = Klass::Entity.new(@table, @id)
end
def test_new
assert_equal("INSERT INTO #{@table} (id) VALUES #{@id}", @entity.save)
end
def test_update
assert_equal("UPDATE #{@table} SET MyCol = 'MyVal' WHERE id = #{@id}", @entity.set("MyCol", "MyVal"))
end
def test_select
assert_equal("SELECT MyCol FROM #{@table} WHERE id = #{@id}", @entity.get("MyCol"))
end
end |
class Status < ActiveRecord::Base
has_many :dataset_implementation_issues
validates_presence_of :name, :description
validates_uniqueness_of :name
end
|
# frozen_string_literal: true
class CreatePositions < ActiveRecord::Migration[6.0]
def change
create_table :positions, id: :uuid do |t|
t.uuid :person_id
t.string :name
t.date :start
t.date :stop
t.timestamps
end
add_index :positions, :person_id
end
end
|
require "capybara"
require "selenium-webdriver"
require "headless"
require "selenium/webdriver"
require "puma"
require 'pludoni_rspec/system_test_chrome_helper'
Capybara.register_driver :chrome do |app|
Capybara::Selenium::Driver.new(app, browser: :chrome, timeout: 300)
end
Capybara.register_driver :headless_chrome do |app|
capabilities = Selenium::WebDriver::Remote::Capabilities.chrome(
'chromeOptions' => {
args: PludoniRspec::Config.chrome_arguments
}
)
Capybara::Selenium::Driver.new app,
browser: :chrome,
desired_capabilities: capabilities
end
Capybara.register_driver :headless_firefox do |app|
options = ::Selenium::WebDriver::Firefox::Options.new
PludoniRspec::Config.firefox_arguments.each do |a|
options.args << a
end
Capybara::Selenium::Driver.new(app, browser: :firefox, options: options)
end
if PludoniRspec::Config.capybara_driver == :headless_chrome
require "chromedriver/helper"
Chromedriver.set_version(PludoniRspec::Config.chrome_driver_version)
Capybara.javascript_driver = :headless_chrome
else
require 'geckodriver/helper'
Capybara.javascript_driver = :headless_firefox
end
RSpec.configure do |c|
c.include PludoniRspec::SystemTestChromeHelper, type: :feature
c.include PludoniRspec::SystemTestChromeHelper, type: :system
c.before(:all, js: true) do
# disable puma output
Capybara.server = :puma, { Silent: true }
end
c.around(:all, js: true) do |ex|
begin
if !@headless and PludoniRspec::Config.wrap_js_spec_in_headless
@headless = Headless.new(destroy_at_exit: true, reuse: true)
@headless.start
end
ex.run
ensure
if @headless and PludoniRspec::Config.destroy_headless
@headless.destroy
end
end
end
end
Capybara.default_max_wait_time = PludoniRspec::Config.capybara_timeout
|
require 'spec_helper'
describe MembersController do
login_user
describe "visit Member Home Page ( Signed in User Only)" do
it "should display Member Home Page" do
get :index
response.should be_success
response.should render_template(:index)
end
end
end
|
class AddConsumerPriceInflationAnnualPercentageToYears < ActiveRecord::Migration
def change
add_column :years, :consumer_price_inflation_annual_percentage, :decimal
end
end
|
# -*- coding: utf-8 -*-
require 'helper'
require 'rails-latex/erb_latex'
require 'ostruct'
require 'pathname'
Rails=OpenStruct.new(:root => TMP_DIR=File.expand_path("../tmp",__FILE__))
class TestLatexToPdf < Test::Unit::TestCase
def setup
super
FileUtils.rm_rf("#{TMP_DIR}/tmp/rails-latex")
end
def teardown
super
LatexToPdf.instance_eval { @config=nil }
end
def write_pdf
FileUtils.mkdir_p(TMP_DIR)
pdf_file=File.join(TMP_DIR,'out.pdf')
File.delete(pdf_file) if File.exist?(pdf_file)
File.open(pdf_file,'wb') do |wio|
wio.write(yield)
end
pdf_file
end
def test_escape
assert_equal "dsf \\textless{} \\textgreater{} \\& ! @ \\# \\$ \\% \\textasciicircum{} \\textasciitilde{} \\textbackslash{} fds", LatexToPdf.escape_latex('dsf < > & ! @ # $ % ^ ~ \\ fds')
LatexToPdf.instance_eval{@latex_escaper=nil}
require 'redcloth'
assert_equal "dsf \\textless{} \\textgreater{} \\& ! @ \\# \\$ \\% \\^{} \\~{} \\textbackslash{} fds", LatexToPdf.escape_latex('dsf < > & ! @ # $ % ^ ~ \\ fds')
end
def test_broken_doc_halt_on_error
begin
LatexToPdf.generate_pdf(IO.read(File.expand_path('../test_broken_doc.tex',__FILE__)),{})
fail "Should throw exception"
rescue => e
assert(/^pdflatex failed: See / =~ e.message)
end
end
def test_broken_doc_overriding_halt_on_error
pdf_file=write_pdf do
LatexToPdf.generate_pdf(IO.read(File.expand_path('../test_broken_doc.tex',__FILE__)),{arguments: []})
end
assert_equal "file with error\n\n1\n\n\f", `pdftotext #{pdf_file} -`
end
def test_generate_pdf_one_parse
pdf_file=write_pdf do
LatexToPdf.generate_pdf(IO.read(File.expand_path('../test_doc.tex',__FILE__)),{})
end
assert_equal "The last page is ??.\n\n1\n\n\f", `pdftotext #{pdf_file} -`
assert_equal ["#{TMP_DIR}/tmp/rails-latex/input.log"], Dir["#{TMP_DIR}/tmp/rails-latex/*.log"]
end
def test_generate_pdf_two_parse
pdf_file=write_pdf do
LatexToPdf.config[:parse_twice]=true
LatexToPdf.generate_pdf(IO.read(File.expand_path('../test_doc.tex',__FILE__)),{})
end
assert_equal "The last page is 1.\n\n1\n\n\f", `pdftotext #{pdf_file} -`
assert_equal ["#{TMP_DIR}/tmp/rails-latex/input.log"], Dir["#{TMP_DIR}/tmp/rails-latex/*.log"]
end
def test_generate_pdf_parse_runs
pdf_file=write_pdf do
LatexToPdf.config[:parse_runs]=2
LatexToPdf.generate_pdf(IO.read(File.expand_path('../test_doc.tex',__FILE__)),{})
end
assert_equal "The last page is 1.\n\n1\n\n\f", `pdftotext #{pdf_file} -`
assert_equal ["#{TMP_DIR}/tmp/rails-latex/input.log"], Dir["#{TMP_DIR}/tmp/rails-latex/*.log"]
end
def test_doc_log_written
begin
LatexToPdf.generate_pdf(IO.read(File.expand_path('../test_doc.tex',__FILE__)),{})
assert_equal ["#{TMP_DIR}/tmp/rails-latex/input.log"], Dir["#{TMP_DIR}/tmp/rails-latex/*.log"]
assert( File.read("#{TMP_DIR}/tmp/rails-latex/input.log") =~ /entering extended mode/ )
end
end
end
|
# frozen_string_literal: true
Rails.application.routes.draw do
devise_for :accounts
# For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html
get '/dashboard' => 'accounts#index'
get '/profile/:username' => 'accounts#profile', as: :profile
get 'post/like/:post_id' => 'likes#save_like', as: :like_post
post 'follow/account' => 'accounts#follow_account', as: :follow_account
delete 'unfollow/:account_id' => 'accounts#unfollow_account', as: :unfollow_account
# get 'post/:id' => 'posts#show', as: :post
resources :posts, only: %i[new create show]
resources :comments, only: %i[create destroy]
root to: 'public#homepage'
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.