repo_name
stringlengths
6
97
path
stringlengths
3
341
text
stringlengths
8
1.02M
matthijsgroen/game-of-geese
tasks/cucumber.rake
begin require 'cucumber/rake/task' namespace :cucumber do Cucumber::Rake::Task.new(:ok, 'Run features that should pass') do |t| t.fork = false # You may get faster startup if you set this to false t.profile = 'default' end Cucumber::Rake::Task.new(:wip, 'Run features that are being worked on') do |t| t.fork = false # You may get faster startup if you set this to false t.profile = 'wip' end desc 'Run all features' task :all => [:ok, :wip] end desc 'Alias for cucumber:ok' task :cucumber => 'cucumber:ok' end
matthijsgroen/game-of-geese
features/step_definitions/play_steps.rb
Stel(/^ik heb de volgende spelers met de klok mee:$/) do |table| # table is a Cucumber::Ast::Table # Table structure: # | naam | leeftijd | kleur pion | # | Jan | 12 | zwart | table.map_headers!( 'naam' => :name, 'leeftijd' => :age, 'kleur pion' => :color ) table.map_column!('leeftijd') { |age| age.to_i } table.map_column!('kleur pion') do |dutch_color| map_dutch_color_to_symbol(dutch_color) end table.hashes.each do |player_attributes| add_player(game, player_attributes) end end Stel(/^(\w+) is aan de beurt om te dobbelen$/) do |player_name| while game.active_player.name != player_name game.active_player.play_turn(FixedDie.new(0)) end end Stel(/^Piet gooit altijd (\d+) met de dobbelsteen$/) do |die_value| game.die = FixedDie.new(die_value) end Als(/^de beurt van (\w+) is geweest$/) do |player_name| until game.active_player.name == player_name game.active_player.play_turn(game.die) end game.active_player.play_turn(game.die) end Als(/^(\w+) (?:een ronde later |)(\d+) dobbelt$/) do |player_name, die_value| until game.active_player.name == player_name game.active_player.play_turn(game.die) end game.active_player.play_turn(FixedDie.new(die_value)) end Als(/^er (\d+) speelrondes zijn gespeeld$/) do |round_count| round_count.times { game.play_round } end Dan(/^heeft (\w+) het spel gewonnen$/) do |player_name| expect(game.winner.name).to eql player_name end Dan(/^is (\w+) (?:weer |)aan de beurt om te dobbelen/) do |person_name| expect(game.active_player.name).to eql person_name end Als(/^het hele potje is gespeeld$/) do game.play_round until game.winner end Dan(/^is er een winnaar bekend$/) do expect(game.winner).not_to be_nil end Dan(/^wint deze een prijs!$/) do puts "#{game.winner.name} heeft gewonnen!" end
matthijsgroen/game-of-geese
lib/gosu-formatter/renderers/die_renderer.rb
<filename>lib/gosu-formatter/renderers/die_renderer.rb<gh_stars>0 #:nodoc: class DieRenderer def initialize(window) @die = { value: 1, x: 0, y: 0 } @rolling = false @value = 1 @counter = 0 initialize_die_images(window) end def update_game(game) return unless game @rolling = game[:die][:rolling] if @rolling @die[:x] = 0 @die[:y] = 0 @direction = rand(0..7) @counter = 0 end @value = game[:die][:value] end def update @counter += 1 return unless @counter % 10 == 0 @die[:value] = @value return unless @rolling @die[:value] = rand(1..6) if @counter < 40 move_die unless @counter > 40 end def move_die # 0 1 2 # 7 3 # 6 5 4 @die[:x] += 1 if [2, 3, 4].include? @direction @die[:y] += 1 if [6, 5, 4].include? @direction @die[:x] -= 1 if [0, 7, 6].include? @direction @die[:y] -= 1 if [0, 1, 2].include? @direction end def draw_die(x, y) return unless @die[:value] die = @die_images[@die[:value]] die.draw(x + (@die[:x] * 30), y + (@die[:y] * 30), 2, 0.5, 0.5) end private def initialize_die_images(window) @die_images = {} (1..6).each do |value| path = "app/images/die#{value}.png" @die_images[value] = Gosu::Image.new(window, path, true) end end end
matthijsgroen/game-of-geese
spec/models/person_spec.rb
<reponame>matthijsgroen/game-of-geese<filename>spec/models/person_spec.rb require 'spec_helper' describe Person do describe 'attributes' do it 'has a name' do p = Person.new name: 'Henk' expect(p.name).to eql 'Henk' end it 'has an age' do p = Person.new age: 34 expect(p.age).to eql 34 end end end
matthijsgroen/game-of-geese
app/models/rules/curvet.rb
require_relative './base' module Rules # When a player lands on this space, # he can move one space before the first pawn on the board class Curvet < Base def enter_space(pawn) in_scope_of_player do sorted_pawns = game.pawns.sort { |a, b| b.location <=> a.location } target_pawn = sorted_pawns.index(pawn) - 1 return unless target_pawn >= 0 respecting_rules do pawn.location = sorted_pawns[target_pawn].location + 1 end end end end end
matthijsgroen/game-of-geese
features/support/transformations/location_transformer.rb
@space = /(?:op |)het \d+(?:de|ste) vakje|daar/ Transform(/(?:op |)het (\d+)(?:de|ste) vakje/) do |location| @current_location = location.to_i end Transform(/daar/) do |_arg| @current_location end
matthijsgroen/game-of-geese
app/models/rules/base.rb
module Rules # Base class with # basic functionality # every rule can reuse class Base def apply_to(player) applied_rule = dup applied_rule.player = player applied_rule end def enter_space(_pawn) end def leave_space(pawn, die_value) pawn.location += die_value end def finish_turn? true end def allowed_to_roll? true end attr_accessor :player protected def in_scope_of_player(&block) player.instance_eval(&block) end end end
matthijsgroen/game-of-geese
spec/models/game_spec.rb
require 'spec_helper' require_relative './roles/player' require_relative './roles/board_pawn' describe Game do let(:game) { Game.new } before do game.board = double('board', space_count: 50) end describe '#join' do let(:person) { double('person') } let(:pawn) { double('pawn') } let(:join) { game.join(person, pawn) } subject { join } it 'lists the person in the list of players' do subject expect(game.players).to match_array [person] end describe 'the joined person' do let(:player) do join game.players.first end it_should_behave_like 'a player' end describe 'the joined pawn' do subject do join game.pawns.first end it_should_behave_like 'a board pawn' end end describe '#active_player' do subject { game.active_player } context 'with nobody playing' do it 'is nobody' do expect(subject).to be_nil end end context 'with one player' do let(:person) { double('person') } before do game.join(person, double('pawn')) end it 'the only player joined' do expect(subject).to eql person end end context 'with multiple players' do let(:older_person) { double('older person', age: 15) } let(:young_person) { double('young person', age: 9) } before do game.join(older_person, double('pawn')) game.join(young_person, double('pawn')) end it 'is the youngest player' do expect(subject).to eql young_person end end end describe 'die attribute' do let(:die) { double('die') } it 'can have a die' do game.die = die expect(game.die).to eql die end end describe '#play_round' do subject { game.play_round } let(:young_person) { double('young person', age: 9) } let(:middle_person) { double('middle person', age: 11) } let(:older_person) { double('older person', age: 15) } let(:die) { double('die') } before do game.join(middle_person, double('pawn')) game.join(young_person, double('pawn')) game.join(older_person, double('pawn')) game.die = die end it 'lets each player play a turn offering a die' do expect(young_person).to receive(:play_turn).with(die).ordered do game.next_turn end expect(older_person).to receive(:play_turn).with(die).ordered do game.next_turn end expect(middle_person).to receive(:play_turn).with(die).ordered do game.next_turn end subject end end describe '#winner' do it 'is undetermined by default' do expect(game.winner).to be_nil end describe 'assignment' do let(:young_person) { double('young person', age: 7) } let(:older_person) { double('older person', age: 8) } let(:pawn1) { double('pawn') } let(:pawn2) { double('pawn') } before do game.board = Board.new(40) game.die = double('die', roll: nil, value: 5) game.join(young_person, pawn1) pawn1.location = game.board.space_count - 1 game.join(older_person, pawn2) pawn2.location = game.board.space_count - 1 end it 'is done when a player reaches the end of the board' do expect do game.play_round end.to change { game.winner }.from(nil).to(young_person) end end end describe 'adding game rules to spaces' do it 'allows for setting and getting rules' do rule = double('rule') game.set_rules_for_space(rule, 5) expect(game.get_rules_for_space(5)).to eql rule end end end
matthijsgroen/game-of-geese
spec/spec_helper.rb
root = File.dirname(__FILE__) + '/../app/' Dir["#{root}/**/*.rb"].each do |file| load file end
matthijsgroen/game-of-geese
lib/gosu-formatter/renderers/pawn_renderer.rb
#:nodoc: class PawnRenderer def initialize(window) @pawns = {} initialize_pawn_images(window) end def update_game(game) pawns = game[:players].map { |p| p[:pawn] } if @pawns.size != pawns.size reset_pawns(pawns) else update_pawns(pawns) end end def transition @pawns.each do |_color, p| p[:transition] += 0.05 p[:transition] = 1.0 if p[:transition] > 1.0 end end def draw_pawn(color, x, y) image = @pawn_images[color] image.draw(x, y, 2, 0.5, 0.5) end def draw_pawns(window) @pawns.each do |color, p| x, y = calculate_pawn_position(p, window) draw_pawn(color, x, y) end end private def update_pawns(pawns) pawns.each do |p| color = p[:color] pawn = @pawns[color] next if pawn[:destination] == p[:location] pawn[:source] = pawn[:destination] pawn[:destination] = p[:location] pawn[:transition] = 0.0 end end def calculate_pawn_position(pawn, window) source = window.space_position(pawn[:source]) destination = window.space_position(pawn[:destination]) delta_x = destination.x - source.x delta_y = destination.y - source.y x = source.x + (delta_x * pawn[:transition]) + (pawn[:index] * 5) y = source.y + (delta_y * pawn[:transition]) + (pawn[:index] * 3) [x, y] end def reset_pawns(pawns) @pawns = {} pawns.each_with_index do |p, index| color = p[:color] @pawns[color] = { index: index, destination: p[:location], source: p[:location], transition: 0.0 } end end def initialize_pawn_images(window) @pawn_images = {} [:black, :blue, :green, :purple, :red, :white, :yellow].each do |color| path = "app/images/pawn_#{color}.png" @pawn_images[color] = Gosu::Image.new(window, path, true) end end end
matthijsgroen/game-of-geese
spec/models/rules/goose_space_spec.rb
require 'spec_helper' describe Rules::GooseSpace do let(:game) { Game.new } let(:board) { Board.new 40 } let(:die) { FixedDie.new 5 } let(:pawn) { Pawn.new color: :blue } let(:person) { Person.new age: 8 } before do game.board = board game.die = die game.join person, pawn end it 'doubles the amount of distance covered' do game.set_rules_for_space described_class.new, 5 game.play_round expect(pawn.location).to eql 10 end end
matthijsgroen/game-of-geese
spec/models/roles/player.rb
<reponame>matthijsgroen/game-of-geese<gh_stars>0 shared_examples_for 'a player' do it 'has a pawn to play' do expect(player.pawn).to eql pawn end describe '#play_turn' do let(:pawn) { double('pawn').extend(BoardPawn) } let(:die) { double('die', roll: nil, value: 6) } subject { player.play_turn(die) } before do player.pawn = pawn pawn.location = 4 end it 'moves the pawn forward using the outcome of the die' do subject expect(player.pawn.location).to eql 10 end it 'ends the turn' do expect(game).to receive(:next_turn) subject end end end
matthijsgroen/game-of-geese
app/models/person.rb
<reponame>matthijsgroen/game-of-geese # Person that will play our game class Person attr_reader :name, :age def initialize(attributes) @name = attributes[:name] @age = attributes[:age] end end
matthijsgroen/game-of-geese
app/models/pawn.rb
<reponame>matthijsgroen/game-of-geese # A physical pawn on the playing field class Pawn attr_reader :color def initialize(attributes) @color = attributes[:color] end end
matthijsgroen/game-of-geese
app/models/game.rb
# Our 'concept' of the game, maintaining the rules of the game class Game attr_reader :players attr_accessor :die, :board attr_reader :winner def initialize @players = [] @rules = {} @players.extend PlayerCircle end def join(person, pawn) player = person.extend Player player.pawn = pawn player.game = self player.place_pawn_on_board @players.push player end def pawns players.map(&:pawn) end # method name suggestion from: # http://english.stackexchange.com/questions/117734 def active_player @active_player ||= players.start end def next_turn @winner = active_player if active_player.pawn.location >= board.space_count @active_player = @players.next_after active_player end def play_round return if winner current_player = active_player round_finished = false until round_finished active_player.play_turn(die) round_finished = (active_player == current_player) || winner end end def set_rules_for_space(rules, space) @rules[space] = rules end def get_rules_for_space(space) @rules[space] || Rules::Base.new end end
matthijsgroen/game-of-geese
features/step_definitions/game_rule_steps.rb
Stel(/^(#{space}) is een ganzenvakje$/) do |location| game.set_rules_for_space(Rules::GooseSpace.new, location) end Stel(/^(#{space}) mag je nogmaals dobbelen$/) do |location| game.set_rules_for_space(Rules::RollAgain.new, location) end Stel(/^alleen als je minder dan (\d+) had gegooid$/) do |die_value| rules = game.get_rules_for_space(current_location) rules.max_die_value = die_value - 1 end Stel(/^(#{space}) is een "(.*?)"$/) do |location, label| game.board.set_label_for_space(label, location) end Stel(/^(#{space}) (?:mag|moet) je (?:verder |terug |)naar vakje (\d+)$/) \ do |location, destination| game.set_rules_for_space Rules::GotoSpace.new(destination), location end Stel(/^(#{space}) moet je (\d+) (?:beurt|beurten) overslaan$/) \ do |location, turns_to_skip| game.set_rules_for_space Rules::SkipTurn.new(turns_to_skip), location end Stel(/^(#{space}) is een bokkesprong$/) do |location| game.set_rules_for_space Rules::Curvet.new, location end Stel(/^(#{space}) is een put$/) do |location| game.set_rules_for_space Rules::Well.new, location end Stel(/^de volgende vakjes zijn ganzenvakjes:$/) do |table| # table is a Cucumber::Ast::Table # Table structure: # | vakje | table.map_headers!( 'vakje' => :location ) table.map_column!('vakje') { |location| location.to_i } table.hashes.each do |location_attributes| game.set_rules_for_space( Rules::GooseSpace.new, location_attributes[:location] ) end end
matthijsgroen/game-of-geese
app/models/roles/player.rb
# The role of a person playing game of goose module Player attr_accessor :pawn attr_accessor :game def place_pawn_on_board pawn.extend BoardPawn respecting_rules do pawn.location = 0 end end def play_turn(die) @die = die respecting_rules do move_pawn_using_die end finish_turn @die = nil end def allowed_to_play? active_rule.allowed_to_roll? end private attr_reader :active_rule, :die def move_pawn_using_die die.roll active_rule.leave_space(pawn, die.value) end def finish_turn return unless active_rule.finish_turn? game.next_turn end def respecting_rules yield rules = game.get_rules_for_space(pawn.location) @active_rule = rules.apply_to(self) @active_rule.enter_space(pawn) end end
matthijsgroen/game-of-geese
app/models/rules/roll_again.rb
require_relative './base' module Rules # Allows the player to roll again class RollAgain < Base attr_accessor :max_die_value def finish_turn? return false unless max_die_value die_value = in_scope_of_player { die.value } die_value > max_die_value end end end
matthijsgroen/game-of-geese
app/models/board.rb
<reponame>matthijsgroen/game-of-geese # The gameboard with spaces to move pawns across class Board attr_reader :space_count def initialize(space_count) @space_count = space_count @labels = {} end def set_label_for_space(label, space) @labels[space] = label end def label_for_space(space) @labels[space] end end
matthijsgroen/game-of-geese
lib/gosu-formatter/formatter.rb
<reponame>matthijsgroen/game-of-geese require 'cucumber/formatter/pretty' require 'drb/drb' require_relative './listeners/die_listener' require_relative './listeners/pawn_listener' module Cucumber module Formatter # Creates a layout on screen to show the cucumber steps # and the active state of the game class Demo < Pretty class << self attr_accessor :active attr_accessor :instance def update_game(game) @game = game add_game_hooks(game) struct = create_game_struct(game) send_game_struct_to_view(struct) end def update struct = create_game_struct(game) send_game_struct_to_view(struct) sleep 1.0 end def roll(value) struct = create_game_struct(game) struct[:die] = { rolling: true, value: value } send_game_struct_to_view(struct) sleep 1.0 end private attr_reader :game def add_game_hooks(game) return unless game add_listener(game.die, DieListener) game.players.each do |p| add_listener(p.pawn, PawnListener) end end def add_listener(obj, listener) return unless obj obj_modules = (class << obj; self; end).included_modules return if obj_modules.include? listener obj.extend listener obj.formatter_listener = self end def send_game_struct_to_view(game_struct) with_remote_game do |remote| remote.game_struct = game_struct end end def with_remote_game @remotegame ||= DRbObject.new_with_uri('druby://localhost:8787') yield @remotegame rescue DRb::DRbConnError # Our client is not started! spawn 'ruby lib/gosu-formatter/remote_client.rb' sleep 1 retry end def create_game_struct(game) return {} unless game { board: { space_count: game.board.space_count }, rules: create_rules_struct(game), die: { value: game.die.value, rolling: false }, players: create_players_struct(game.players, game.active_player, game.winner) } end def create_rules_struct(game) rules = {} game.board.space_count.times do |index| rule = game.get_rules_for_space(index) next unless rule && rule.class != Rules::Base rules[index] = { rule: rule.class.name, description: game.board.label_for_space(index) } end rules end def create_players_struct(players, active_player, winner) players.map do |p| { name: p.name, age: p.age, active: p == active_player, winner: p == winner, pawn: create_pawn_struct(p.pawn) } end end def create_pawn_struct(pawn) { color: pawn.color, location: pawn.location } end end def initialize(*) self.class.active = true self.class.instance ||= self super end end end end
matthijsgroen/game-of-geese
app/models/rules/goto_space.rb
require_relative './base' module Rules # Brings the player to a new location class GotoSpace < Base def initialize(destination) @destination = destination end def enter_space(pawn) local_destination = destination in_scope_of_player do respecting_rules do pawn.location = local_destination end end end private attr_reader :destination end end
matthijsgroen/game-of-geese
lib/gosu-formatter/game_window.rb
require 'gosu' require_relative 'space_generator' require_relative './renderers/pawn_renderer' require_relative './renderers/die_renderer' require_relative './renderers/board_renderer' # this is the main game window class GameWindow < Gosu::Window attr_accessor :spaces attr_accessor :update COLOR_WHITE = Gosu::Color.new(0xFFFFFFFF) def initialize super(800, 600, false) self.caption = 'Game of geese' @spaces = [] @pawn_renderer = PawnRenderer.new(self) @die_renderer = DieRenderer.new(self) @board_renderer = BoardRenderer.new(self) @font = Gosu::Font.new(self, Gosu.default_font_name, 20) end def game_struct=(game) @update = true @game = game @pawn_renderer.update_game(game) @die_renderer.update_game(game) end def update @pawn_renderer.transition @die_renderer.update end def draw return unless @game clear draw_board(@game[:board]) draw_players(@game[:players], 90, 150) @die_renderer.draw_die(400, 250) @pawn_renderer.draw_pawns(self) end def draw_players(players, x, y) players.each_with_index do |p, i| @pawn_renderer.draw_pawn(p[:pawn][:color], x, y + (30 * i)) label = p[:name] label += ' <' if p[:active] label += ' WINNAAR!' if p[:winner] @font.draw(label, x + 30, y + (30 * i), 1, 1, 1, p[:active] ? 0xff000000 : 0x9f000000) end end def draw_board(board) @spaces = define_spaces(board[:space_count]) if @update @update = false @board_renderer.render_board(@spaces, @game[:rules]) end Space = Struct.new(:x, :y) def space_position(index) s = @spaces[[index, @spaces.size - 1].min] Space.new(s[:topleft_x], s[:topleft_y]) end private def define_spaces(space_count) generator = SpaceGenerator.new(700, 500, cell_spacing: 60, row_spacing: 70) generator.generate_spaces(space_count + 1) generator.spaces end def clear draw_quad( 0, 0, COLOR_WHITE, 800, 0, COLOR_WHITE, 800, 600, COLOR_WHITE, 0, 600, COLOR_WHITE, 0 ) end end
matthijsgroen/game-of-geese
spec/models/rules/base_spec.rb
require 'spec_helper' describe Rules::Base do describe '#apply_to' do let(:player) { double('player') } it 'makes a duplicate with an assigned player' do inst1 = described_class.new inst2 = inst1.apply_to(player) expect(inst1.player).to be_nil expect(inst2.player).to eql player expect(inst2).to be_a described_class end end end
matthijsgroen/game-of-geese
spec/models/roles/board_pawn.rb
<filename>spec/models/roles/board_pawn.rb shared_examples_for 'a board pawn' do it 'has a location on the board' do expect(subject.location).to eql 0 end end
matthijsgroen/game-of-geese
app/models/rules/goose_space.rb
<reponame>matthijsgroen/game-of-geese require_relative './base' module Rules # When a player lands on this space, # he can move the amount of value of the dice again class GooseSpace < Base def enter_space(pawn) in_scope_of_player do respecting_rules do pawn.location += die.value end end end end end
matthijsgroen/game-of-geese
features/step_definitions/board_setup_steps.rb
<filename>features/step_definitions/board_setup_steps.rb Stel(/^ik heb een speelbord met (\d+) vakjes$/) do |space_count| @game = Game.new game.board = Board.new(space_count) game.die = Die.new end Stel(/^alle pionnen staan op het startvakje$/) do # No assertion at the moment that requires implementation here end Stel(/^de (\w+) pion staat (#{space})$/) do |dutch_pawn_color, location| pawn_color = map_dutch_color_to_symbol(dutch_pawn_color) pawn = game.pawns.find { |p| p.color == pawn_color } pawn.location = location end Dan(/^staat de (\w+) pion (#{space})$/) do |dutch_color, location| pawn_color = map_dutch_color_to_symbol(dutch_color) pawn = game.pawns.find { |p| p.color == pawn_color } expect(pawn.location).to eql location end Dan(/^is de bord opstelling als volgt:$/) do |table| # table is a Cucumber::Ast::Table # | pion | vakje | table.map_headers!( 'pion' => :color, 'vakje' => :location ) table.map_column!('vakje') { |location| location.to_i } table.map_column!('pion') do |dutch_color| map_dutch_color_to_symbol(dutch_color) end expected_pawn_setup = Hash[ table.hashes.map { |e| [e[:color], e[:location]] } ] actual_pawn_setup = Hash[ game.pawns.map { |a| [a.color, a.location] } ] expect(actual_pawn_setup).to eql expected_pawn_setup end Dan(/^de pionnen staan als volgt opgesteld:$/) do |table| # table is a Cucumber::Ast::Table # | pion | vakje | table.map_headers!( 'pion' => :color, 'vakje' => :location ) table.map_column!('vakje') { |location| location.to_i } table.map_column!('pion') do |dutch_color| map_dutch_color_to_symbol(dutch_color) end table.hashes.each do |data| pawn = game.pawns.find { |p| p.color == data[:color] } pawn.location = data[:location] end end
matthijsgroen/game-of-geese
spec/models/board_spec.rb
<gh_stars>0 require 'spec_helper' describe Board do let(:space_count) { 30 } let(:board) { Board.new space_count } describe '#spaces' do it 'returns the amount of spaces on the board' do expect(board.space_count).to eql space_count end end describe '#set_label_for_space' do it 'attaches a label to a space' do board.set_label_for_space('Lorem Ipsum', 5) expect(board.label_for_space(5)).to eql 'Lorem Ipsum' end end end
matthijsgroen/game-of-geese
lib/gosu-formatter/listeners/die_listener.rb
<filename>lib/gosu-formatter/listeners/die_listener.rb # tell gosu when die is rolled module DieListener attr_accessor :formatter_listener def roll super.tap { formatter_listener.roll(value) } end end
matthijsgroen/game-of-geese
spec/models/rules/curvet_spec.rb
<reponame>matthijsgroen/game-of-geese<gh_stars>0 require 'spec_helper' describe Rules::Curvet do let(:game) { Game.new } let(:board) { Board.new 40 } let(:die) { FixedDie.new 5 } let(:pawn) { Pawn.new color: :blue } let(:person) { Person.new age: 8 } let(:first_person) { Person.new age: 9 } let(:first_pawn) { Pawn.new color: :red } before do game.board = board game.die = die game.join person, pawn game.join first_person, first_pawn end it 'moves the pawn one space before the first pawn' do first_pawn.location = 13 rule = described_class.new game.set_rules_for_space rule, 5 expect do game.active_player.play_turn(die) end.to change { pawn.location }.to 14 end it 'does not move the pawn when first pawn' do first_pawn.location = 2 rule = described_class.new game.set_rules_for_space rule, 5 expect do game.active_player.play_turn(die) end.to change { pawn.location }.to 5 end end
matthijsgroen/game-of-geese
features/support/env.rb
<gh_stars>0 root = File.dirname(__FILE__) + '/../../app/' [:space, :current_location, :game].each do |reader| define_method(reader) do instance_variable_get("@#{reader}") end end Dir["#{root}/**/*.rb"].each do |file| load file end
matthijsgroen/game-of-geese
features/support/demo_mode.rb
require_relative '../../lib/gosu-formatter/formatter' AfterStep do formatter = Cucumber::Formatter::Demo formatter.update_game(@game) if formatter.active && @game end
matthijsgroen/game-of-geese
app/models/die.rb
# A standard die with 6 faces class Die attr_reader :value def roll @value = rand(1..6) end end
matthijsgroen/game-of-geese
features/support/helpers/dutch_helpers.rb
# Helpers to translate dutch names into # english / ruby module DutchHelpers # remap colors to english symbols def map_dutch_color_to_symbol(dutch_color) { 'zwart' => :black, 'blauw' => :blue, 'paars' => :purple, 'geel' => :yellow, 'groen' => :green, 'rood' => :red, 'wit' => :white }[simplified_dutch_color dutch_color] end def simplified_dutch_color(dutch_color) return 'rood' if dutch_color == 'rode' return 'wit' if dutch_color == 'witte' return dutch_color[0...-1] if dutch_color[-1] == 'e' dutch_color end end World(DutchHelpers)
matthijsgroen/game-of-geese
app/models/fixed_die.rb
# A fixed die that always returns a pre-defined value class FixedDie attr_reader :value def initialize(fixed_value) @value = fixed_value end def roll end end
asimcan/vagrant-boxes
centos-postgres/manifests/modules/iptables/spec/classes/iptables_spec.rb
<filename>centos-postgres/manifests/modules/iptables/spec/classes/iptables_spec.rb require "#{File.join(File.dirname(__FILE__),'..','spec_helper.rb')}" describe 'iptables' do let(:node) { 'iptables1.example42.com' } let(:facts) { { :operatingsystem => 'ubuntu', :osver_maj => 12 } } it { should contain_iptables__concat_emitter('v4') } it { should_not contain_iptables__concat_emitter('v6') } end describe 'iptables' do let(:node) { 'iptables2.example42.com' } let(:facts) { { :operatingsystem => 'ubuntu', :osver_maj => 12 } } let(:params) { { :enable_v6 => 'true' } } it { should contain_iptables__concat_emitter('v4') } it { should contain_iptables__concat_emitter('v6') } end
jetthoughts/bundler
spec/install/process_lock_spec.rb
# frozen_string_literal: true RSpec.describe "process lock spec" do describe "when an install operation is already holding a process lock" do before { FileUtils.mkdir_p(default_bundle_path) } it "will not run a second concurrent bundle install until the lock is released" do thread = Thread.new do Bundler::ProcessLock.lock(default_bundle_path) do sleep 1 # ignore quality_spec expect(the_bundle).not_to include_gems "rack 1.0" end end install_gemfile! <<-G source "file://#{gem_repo1}" gem "rack" G thread.join expect(the_bundle).to include_gems "rack 1.0" end end end
jetthoughts/bundler
spec/commands/doctor_spec.rb
<reponame>jetthoughts/bundler # frozen_string_literal: true require "stringio" require "bundler/cli" require "bundler/cli/doctor" RSpec.describe "bundle doctor" do before(:each) do @stdout = StringIO.new [:error, :warn].each do |method| allow(Bundler.ui).to receive(method).and_wrap_original do |m, message| m.call message @stdout.puts message end end end it "exits with no message if the installed gem has no C extensions" do install_gemfile! <<-G source "file://#{gem_repo1}" gem "rack" G expect { Bundler::CLI::Doctor.new({}).run }.not_to raise_error expect(@stdout.string).to be_empty end it "exits with no message if the installed gem's C extension dylib breakage is fine" do install_gemfile! <<-G source "file://#{gem_repo1}" gem "rack" G doctor = Bundler::CLI::Doctor.new({}) expect(doctor).to receive(:bundles_for_gem).exactly(2).times.and_return ["/path/to/rack/rack.bundle"] expect(doctor).to receive(:dylibs).exactly(2).times.and_return ["/usr/lib/libSystem.dylib"] allow(File).to receive(:exist?).and_call_original allow(File).to receive(:exist?).with("/usr/lib/libSystem.dylib").and_return(true) expect { doctor.run }.not_to(raise_error, @stdout.string) expect(@stdout.string).to be_empty end it "exits with a message if one of the linked libraries is missing" do install_gemfile! <<-G source "file://#{gem_repo1}" gem "rack" G doctor = Bundler::CLI::Doctor.new({}) expect(doctor).to receive(:bundles_for_gem).exactly(2).times.and_return ["/path/to/rack/rack.bundle"] expect(doctor).to receive(:dylibs).exactly(2).times.and_return ["/usr/local/opt/icu4c/lib/libicui18n.57.1.dylib"] allow(File).to receive(:exist?).and_call_original allow(File).to receive(:exist?).with("/usr/local/opt/icu4c/lib/libicui18n.57.1.dylib").and_return(false) expect { doctor.run }.to raise_error(Bundler::ProductionError, strip_whitespace(<<-E).strip), @stdout.string The following gems are missing OS dependencies: * bundler: /usr/local/opt/icu4c/lib/libicui18n.57.1.dylib * rack: /usr/local/opt/icu4c/lib/libicui18n.57.1.dylib E end end
jetthoughts/bundler
lib/bundler/deprecate.rb
# frozen_string_literal: true begin require "rubygems/deprecate" rescue LoadError # it's fine if it doesn't exist on the current RubyGems... nil end module Bundler if defined? Bundler::Deprecate # nothing to do! elsif defined? ::Deprecate Deprecate = ::Deprecate elsif defined? Gem::Deprecate Deprecate = Gem::Deprecate else class Deprecate end end unless Deprecate.respond_to?(:skip_during) def Deprecate.skip_during original = skip self.skip = true yield ensure self.skip = original end end unless Deprecate.respond_to?(:skip) def Deprecate.skip @skip ||= false end end unless Deprecate.respond_to?(:skip=) def Deprecate.skip=(skip) @skip = skip end end end
jetthoughts/bundler
lib/bundler/vendor/molinillo/lib/molinillo/dependency_graph/vertex.rb
<reponame>jetthoughts/bundler # frozen_string_literal: true module Bundler::Molinillo class DependencyGraph # A vertex in a {DependencyGraph} that encapsulates a {#name} and a # {#payload} class Vertex # @return [String] the name of the vertex attr_accessor :name # @return [Object] the payload the vertex holds attr_accessor :payload # @return [Array<Object>] the explicit requirements that required # this vertex attr_reader :explicit_requirements # @return [Boolean] whether the vertex is considered a root vertex attr_accessor :root alias root? root # Initializes a vertex with the given name and payload. # @param [String] name see {#name} # @param [Object] payload see {#payload} def initialize(name, payload) @name = name.frozen? ? name : name.dup.freeze @payload = payload @explicit_requirements = [] @outgoing_edges = [] @incoming_edges = [] end # @return [Array<Object>] all of the requirements that required # this vertex def requirements (incoming_edges.map(&:requirement) + explicit_requirements).uniq end # @return [Array<Edge>] the edges of {#graph} that have `self` as their # {Edge#origin} attr_accessor :outgoing_edges # @return [Array<Edge>] the edges of {#graph} that have `self` as their # {Edge#destination} attr_accessor :incoming_edges # @return [Array<Vertex>] the vertices of {#graph} that have an edge with # `self` as their {Edge#destination} def predecessors incoming_edges.map(&:origin) end # @return [Array<Vertex>] the vertices of {#graph} where `self` is a # {#descendent?} def recursive_predecessors vertices = predecessors vertices += Compatibility.flat_map(vertices, &:recursive_predecessors) vertices.uniq! vertices end # @return [Array<Vertex>] the vertices of {#graph} that have an edge with # `self` as their {Edge#origin} def successors outgoing_edges.map(&:destination) end # @return [Array<Vertex>] the vertices of {#graph} where `self` is an # {#ancestor?} def recursive_successors vertices = successors vertices += Compatibility.flat_map(vertices, &:recursive_successors) vertices.uniq! vertices end # @return [String] a string suitable for debugging def inspect "#{self.class}:#{name}(#{payload.inspect})" end # @return [Boolean] whether the two vertices are equal, determined # by a recursive traversal of each {Vertex#successors} def ==(other) return true if equal?(other) shallow_eql?(other) && successors.to_set == other.successors.to_set end # @param [Vertex] other the other vertex to compare to # @return [Boolean] whether the two vertices are equal, determined # solely by {#name} and {#payload} equality def shallow_eql?(other) return true if equal?(other) other && name == other.name && payload == other.payload end alias eql? == # @return [Fixnum] a hash for the vertex based upon its {#name} def hash name.hash end # Is there a path from `self` to `other` following edges in the # dependency graph? # @return true iff there is a path following edges within this {#graph} def path_to?(other) equal?(other) || successors.any? { |v| v.path_to?(other) } end alias descendent? path_to? # Is there a path from `other` to `self` following edges in the # dependency graph? # @return true iff there is a path following edges within this {#graph} def ancestor?(other) other.path_to?(self) end alias is_reachable_from? ancestor? end end end
jetthoughts/bundler
spec/runtime/gem_tasks_spec.rb
# frozen_string_literal: true RSpec.describe "require 'bundler/gem_tasks'" do before :each do bundled_app("foo.gemspec").open("w") do |f| f.write <<-GEMSPEC Gem::Specification.new do |s| s.name = "foo" end GEMSPEC end bundled_app("Rakefile").open("w") do |f| f.write <<-RAKEFILE $:.unshift("#{bundler_path}") require "bundler/gem_tasks" RAKEFILE end end it "includes the relevant tasks" do with_gem_path_as(Spec::Path.base_system_gems.to_s) do sys_exec "ruby -S rake -T" end expect(err).to eq("") expected_tasks = [ "rake build", "rake clean", "rake clobber", "rake install", "rake release[remote]", ] tasks = out.lines.to_a.map {|s| s.split("#").first.strip } expect(tasks & expected_tasks).to eq(expected_tasks) expect(exitstatus).to eq(0) if exitstatus end it "adds 'pkg' to rake/clean's CLOBBER" do require "bundler/gem_tasks" expect(CLOBBER).to include("pkg") end end
jetthoughts/bundler
spec/install/force_spec.rb
# frozen_string_literal: true RSpec.describe "bundle install" do %w[force redownload].each do |flag| describe_opts = {} describe_opts[:bundler] = "< 2" if flag == "force" describe "with --#{flag}", describe_opts do before :each do gemfile <<-G source "file://#{gem_repo1}" gem "rack" G end it "re-installs installed gems" do rack_lib = default_bundle_path("gems/rack-1.0.0/lib/rack.rb") bundle! :install rack_lib.open("w") {|f| f.write("blah blah blah") } bundle! :install, flag => true expect(out).to include "Installing rack 1.0.0" expect(rack_lib.open(&:read)).to eq("RACK = '1.0.0'\n") expect(the_bundle).to include_gems "rack 1.0.0" end it "works on first bundle install" do bundle! :install, flag => true expect(out).to include "Installing rack 1.0.0" expect(the_bundle).to include_gems "rack 1.0.0" end context "with a git gem" do let!(:ref) { build_git("foo", "1.0").ref_for("HEAD", 11) } before do gemfile <<-G gem "foo", :git => "#{lib_path("foo-1.0")}" G end it "re-installs installed gems" do foo_lib = default_bundle_path("bundler/gems/foo-1.0-#{ref}/lib/foo.rb") bundle! :install foo_lib.open("w") {|f| f.write("blah blah blah") } bundle! :install, flag => true expect(foo_lib.open(&:read)).to eq("FOO = '1.0'\n") expect(the_bundle).to include_gems "foo 1.0" end it "works on first bundle install" do bundle! :install, flag => true expect(the_bundle).to include_gems "foo 1.0" end end end end end
jetthoughts/bundler
spec/bundler/source/git/git_proxy_spec.rb
# frozen_string_literal: true RSpec.describe Bundler::Source::Git::GitProxy do let(:uri) { "https://github.com/bundler/bundler.git" } subject { described_class.new(Pathname("path"), uri, "HEAD") } context "with configured credentials" do it "adds username and password to URI" do Bundler.settings.temporary(uri => "u:p") expect(subject).to receive(:git_retry).with(match("https://u:p@github.com/bundler/bundler.git")) subject.checkout end it "adds username and password to URI for host" do Bundler.settings.temporary("github.com" => "u:p") expect(subject).to receive(:git_retry).with(match("https://u:p@github.com/bundler/bundler.git")) subject.checkout end it "does not add username and password to mismatched URI" do Bundler.settings.temporary("https://u:p@github.com/bundler/bundler-mismatch.git" => "u:p") expect(subject).to receive(:git_retry).with(match(uri)) subject.checkout end it "keeps original userinfo" do Bundler.settings.temporary("github.com" => "u:p") original = "https://orig:info@github.com/bundler/bundler.git" subject = described_class.new(Pathname("path"), original, "HEAD") expect(subject).to receive(:git_retry).with(match(original)) subject.checkout end end describe "#version" do context "with a normal version number" do before do expect(subject).to receive(:git).with("--version"). and_return("git version 1.2.3") end it "returns the git version number" do expect(subject.version).to eq("1.2.3") end it "does not raise an error when passed into Gem::Version.create" do expect { Gem::Version.create subject.version }.not_to raise_error end end context "with a OSX version number" do before do expect(subject).to receive(:git).with("--version"). and_return("git version 1.2.3 (Apple Git-BS)") end it "strips out OSX specific additions in the version string" do expect(subject.version).to eq("1.2.3") end it "does not raise an error when passed into Gem::Version.create" do expect { Gem::Version.create subject.version }.not_to raise_error end end context "with a msysgit version number" do before do expect(subject).to receive(:git).with("--version"). and_return("git version 1.2.3.msysgit.0") end it "strips out msysgit specific additions in the version string" do expect(subject.version).to eq("1.2.3") end it "does not raise an error when passed into Gem::Version.create" do expect { Gem::Version.create subject.version }.not_to raise_error end end end describe "#full_version" do context "with a normal version number" do before do expect(subject).to receive(:git).with("--version"). and_return("git version 1.2.3") end it "returns the git version number" do expect(subject.full_version).to eq("1.2.3") end end context "with a OSX version number" do before do expect(subject).to receive(:git).with("--version"). and_return("git version 1.2.3 (Apple Git-BS)") end it "does not strip out OSX specific additions in the version string" do expect(subject.full_version).to eq("1.2.3 (Apple Git-BS)") end end context "with a msysgit version number" do before do expect(subject).to receive(:git).with("--version"). and_return("git version 1.2.3.msysgit.0") end it "does not strip out msysgit specific additions in the version string" do expect(subject.full_version).to eq("1.2.3.msysgit.0") end end end end
jetthoughts/bundler
lib/bundler/current_ruby.rb
<gh_stars>1-10 # frozen_string_literal: true module Bundler # Returns current version of Ruby # # @return [CurrentRuby] Current version of Ruby def self.current_ruby @current_ruby ||= CurrentRuby.new end class CurrentRuby KNOWN_MINOR_VERSIONS = %w[ 1.8 1.9 2.0 2.1 2.2 2.3 2.4 2.5 ].freeze KNOWN_MAJOR_VERSIONS = KNOWN_MINOR_VERSIONS.map {|v| v.split(".", 2).first }.uniq.freeze KNOWN_PLATFORMS = %w[ jruby maglev mingw mri mswin mswin64 rbx ruby x64_mingw ].freeze def ruby? !mswin? && (!defined?(RUBY_ENGINE) || RUBY_ENGINE == "ruby" || RUBY_ENGINE == "rbx" || RUBY_ENGINE == "maglev") end def mri? !mswin? && (!defined?(RUBY_ENGINE) || RUBY_ENGINE == "ruby") end def rbx? ruby? && defined?(RUBY_ENGINE) && RUBY_ENGINE == "rbx" end def jruby? defined?(RUBY_ENGINE) && RUBY_ENGINE == "jruby" end def maglev? defined?(RUBY_ENGINE) && RUBY_ENGINE == "maglev" end def mswin? Bundler::WINDOWS end def mswin64? Bundler::WINDOWS && Bundler.local_platform != Gem::Platform::RUBY && Bundler.local_platform.os == "mswin64" && Bundler.local_platform.cpu == "x64" end def mingw? Bundler::WINDOWS && Bundler.local_platform != Gem::Platform::RUBY && Bundler.local_platform.os == "mingw32" && Bundler.local_platform.cpu != "x64" end def x64_mingw? Bundler::WINDOWS && Bundler.local_platform != Gem::Platform::RUBY && Bundler.local_platform.os == "mingw32" && Bundler.local_platform.cpu == "x64" end (KNOWN_MINOR_VERSIONS + KNOWN_MAJOR_VERSIONS).each do |version| trimmed_version = version.tr(".", "") define_method(:"on_#{trimmed_version}?") do RUBY_VERSION.start_with?("#{version}.") end KNOWN_PLATFORMS.each do |platform| define_method(:"#{platform}_#{trimmed_version}?") do send(:"#{platform}?") && send(:"on_#{trimmed_version}?") end end end end end
jetthoughts/bundler
bundler.gemspec
<reponame>jetthoughts/bundler # coding: utf-8 # frozen_string_literal: true require File.expand_path("../lib/bundler/version", __FILE__) require "shellwords" Gem::Specification.new do |s| s.name = "bundler" s.version = Bundler::VERSION s.license = "MIT" s.authors = [ "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>" ] s.email = ["<EMAIL>"] s.homepage = "http://bundler.io" s.summary = "The best way to manage your application's dependencies" s.description = "Bundler manages an application's dependencies through its entire life, across many machines, systematically and repeatably" if s.respond_to?(:metadata=) s.metadata = { "bug_tracker_uri" => "http://github.com/bundler/bundler/issues", "changelog_uri" => "https://github.com/bundler/bundler/blob/master/CHANGELOG.md", "homepage_uri" => "https://bundler.io/", "source_code_uri" => "http://github.com/bundler/bundler/", } end if s.version >= Gem::Version.new("2.a".dup) s.required_ruby_version = ">= 2.3.0" s.required_rubygems_version = ">= 2.5.0" else s.required_ruby_version = ">= 1.8.7" s.required_rubygems_version = ">= 1.3.6" end s.add_development_dependency "automatiek", "~> 0.1.0" s.add_development_dependency "mustache", "0.99.6" s.add_development_dependency "rake", "~> 10.0" s.add_development_dependency "rdiscount", "~> 2.2" s.add_development_dependency "ronn", "~> 0.7.3" s.add_development_dependency "rspec", "~> 3.6" s.files = `git -C #{Shellwords.escape File.dirname(__FILE__)} ls-files -z`.split("\x0").select {|f| f.match(%r{^(lib|exe)/}) } # we don't check in man pages, but we need to ship them because # we use them to generate the long-form help for each command. s.files += Dir.glob("man/**/*") # Include the CHANGELOG.md, LICENSE.md, README.md manually s.files += %w[CHANGELOG.md LICENSE.md README.md] # include the gemspec itself because warbler breaks w/o it s.files += %w[bundler.gemspec] s.bindir = "exe" s.executables = %w[bundle bundler] s.require_paths = ["lib"] end
jetthoughts/bundler
spec/plugins/hook_spec.rb
<gh_stars>1-10 # frozen_string_literal: true RSpec.describe "hook plugins" do before do build_repo2 do build_plugin "before-install-plugin" do |s| s.write "plugins.rb", <<-RUBY Bundler::Plugin::API.hook "before-install-all" do |deps| puts "gems to be installed \#{deps.map(&:name).join(", ")}" end RUBY end end bundle "plugin install before-install-plugin --source file://#{gem_repo2}" end it "runs after a rubygem is installed" do install_gemfile <<-G source "file://#{gem_repo1}" gem "rake" gem "rack" G expect(out).to include "gems to be installed rake, rack" end end
jetthoughts/bundler
lib/bundler/process_lock.rb
<gh_stars>1-10 # frozen_string_literal: true module Bundler class ProcessLock def self.lock(bundle_path = Bundler.bundle_path) lock_file_path = File.join(bundle_path, "bundler.lock") has_lock = false File.open(lock_file_path, "w") do |f| f.flock(File::LOCK_EX) has_lock = true yield f.flock(File::LOCK_UN) end rescue Errno::EACCES, Errno::ENOLCK # In the case the user does not have access to # create the lock file or is using NFS where # locks are not available we skip locking. yield ensure FileUtils.rm_f(lock_file_path) if has_lock end end end
jetthoughts/bundler
spec/install/failure_spec.rb
<filename>spec/install/failure_spec.rb # frozen_string_literal: true RSpec.describe "bundle install" do context "installing a gem fails" do it "prints out why that gem was being installed" do build_repo2 do build_gem "activesupport", "2.3.2" do |s| s.extensions << "Rakefile" s.write "Rakefile", <<-RUBY task :default do abort "make installing activesupport-2.3.2 fail" end RUBY end end install_gemfile <<-G source "file:#{gem_repo2}" gem "rails" G expect(last_command.bundler_err).to end_with(<<-M.strip) An error occurred while installing activesupport (2.3.2), and Bundler cannot continue. Make sure that `gem install activesupport -v '2.3.2'` succeeds before bundling. In Gemfile: rails was resolved to 2.3.2, which depends on actionmailer was resolved to 2.3.2, which depends on activesupport M end context "because the downloaded .gem was invalid" do before do build_repo4 do build_gem "a" end gem_repo4("gems", "a-1.0.gem").open("w") {|f| f << "<html></html>" } end it "removes the downloaded .gem" do install_gemfile <<-G source "file:#{gem_repo4}" gem "a" G expect(default_bundle_path("cache", "a-1.0.gem")).not_to exist end end end end
jetthoughts/bundler
lib/bundler/cli/list.rb
<reponame>jetthoughts/bundler # frozen_string_literal: true module Bundler class CLI::List def initialize(options) @options = options end def run specs = Bundler.load.specs.reject {|s| s.name == "bundler" }.sort_by(&:name) return specs.each {|s| Bundler.ui.info s.name } if @options["name-only"] return Bundler.ui.info "No gems in the Gemfile" if specs.empty? Bundler.ui.info "Gems included by the bundle:" specs.each do |s| Bundler.ui.info " * #{s.name} (#{s.version}#{s.git_version})" end Bundler.ui.info "Use `bundle info` to print more detailed information about a gem" end end end
jetthoughts/bundler
spec/commands/list_spec.rb
<filename>spec/commands/list_spec.rb # frozen_string_literal: true RSpec.describe "bundle list", :bundler => "2" do before do install_gemfile <<-G source "file://#{gem_repo1}" gem "rack" G end context "with name-only option" do it "prints only the name of the gems in the bundle" do bundle "list --name-only" expect(out).to eq "rack" end end context "when no gems are in the gemfile" do before do install_gemfile <<-G source "file://#{gem_repo1}" G end it "prints message saying no gems are in the bundle" do bundle "list" expect(out).to include("No gems in the Gemfile") end end it "lists gems installed in the bundle" do bundle "list" expect(out).to include(" * rack (1.0.0)") end it "aliases the ls command to list" do bundle "ls" expect(out).to include("Gems included by the bundle") end end
jetthoughts/bundler
lib/bundler/cli/binstubs.rb
<reponame>jetthoughts/bundler<gh_stars>0 # frozen_string_literal: true module Bundler class CLI::Binstubs attr_reader :options, :gems def initialize(options, gems) @options = options @gems = gems end def run Bundler.definition.validate_runtime! path_option = options["path"] path_option = nil if path_option && path_option.empty? Bundler.settings.set_command_option :bin, path_option if options["path"] Bundler.settings.set_command_option_if_given :shebang, options["shebang"] installer = Installer.new(Bundler.root, Bundler.definition) if gems.empty? Bundler.ui.error "`bundle binstubs` needs at least one gem to run." exit 1 end gems.each do |gem_name| spec = Bundler.definition.specs.find {|s| s.name == gem_name } unless spec raise GemNotFound, Bundler::CLI::Common.gem_not_found_message( gem_name, Bundler.definition.specs ) end if options[:standalone] next Bundler.ui.warn("Sorry, Bundler can only be run via RubyGems.") if gem_name == "bundler" Bundler.settings.temporary(:path => (Bundler.settings[:path] || Bundler.root)) do installer.generate_standalone_bundler_executable_stubs(spec) end else installer.generate_bundler_executable_stubs(spec, :force => options[:force], :binstubs_cmd => true) end end end end end
lexmag/wizardry
spec/dummy/config/routes.rb
Dummy::Application.routes.draw do resources :products, except: :destroy, path_names: { new: :make } do get :commit, on: :collection has_wizardry end end
lexmag/wizardry
spec/spec_helper.rb
ENV['RAILS_ENV'] = 'test' require File.expand_path('../dummy/config/environment.rb', __FILE__) require 'minitest/autorun' require 'action_controller/test_case' class MiniTest::Spec include ActiveSupport::Testing::SetupAndTeardown end class RoutingSpec < Minitest::Spec include ActionDispatch::Integration::Runner include Rails.application.routes.url_helpers before do @routes = Rails.application.routes end register_spec_type(/Routing/, self) end
lexmag/wizardry
lib/wizardry/base.rb
<gh_stars>1-10 module Wizardry module Base extend ActiveSupport::Concern module ClassMethods def wizardry(*steps) class_attribute :steps, :steps_regexp, instance_writer: false self.steps = steps.map{ |s| s.to_s.inquiry } self.steps_regexp = Regexp.new(steps.join('|')) include WizardryMethods [*Wizardry::ORDINALS.first(steps.size - 1), :last].each do |method| class_eval <<-EOT, __FILE__, __LINE__ + 1 def #{method}_step # def first_step steps.#{method} # steps.first end # end def #{method}_step? # def first_step? current_step == #{method}_step # current_step == first_step end # end EOT end end end module WizardryMethods def current_step @current_step ||= first_step end def current_step=(step) step = step.to_s @current_step = step.inquiry if steps.include?(step) end def next_step steps[current_step_idx + 1] unless last_step? end def previous_step steps[current_step_idx - 1] unless first_step? end def step_title(step = current_step) return if step !~ steps_regexp I18n.translate(step, scope: 'wizardry.steps', default: step.to_s.humanize) end private def current_step_idx steps.index(current_step) end end end end ActiveRecord::Base.send :include, Wizardry::Base
lexmag/wizardry
spec/dummy/app/models/product.rb
<reponame>lexmag/wizardry<filename>spec/dummy/app/models/product.rb<gh_stars>1-10 class Product < ActiveRecord::Base wizardry :initial, :middle, :final end
lexmag/wizardry
spec/wizardry/routes_spec.rb
<reponame>lexmag/wizardry require 'spec_helper' describe 'Wizardry Routing' do it 'must accept wizardry `edit` routes' do assert_recognizes({ controller: 'products', action: 'edit', id: '1', step: 'initial'}, '/products/1/edit/initial') assert_recognizes({ controller: 'products', action: 'edit', id: '1', step: 'middle'}, '/products/1/edit/middle') assert_recognizes({ controller: 'products', action: 'edit', id: '1', step: 'final'}, '/products/1/edit/final') assert '/products/1/initial', edit_product_path(id: 1, step: 'initial') end it 'must accept only valid steps' do assert_raises ActionController::RoutingError do assert_recognizes({ controller: 'products', action: 'edit', id: '1', step: 'fictional'}, '/products/1/edit/fictional') end end it 'must not accept default `edit` route' do assert_raises ActionController::RoutingError do assert_recognizes({ controller: 'products', action: 'edit', id: '1'}, '/products/1/edit') end end it 'must not accept `destroy` route' do assert_raises ActionController::RoutingError do assert_recognizes({ controller: 'products', action: 'destroy', id: '1'}, { path: '/products/1', method: :delete }) end end it 'must accept routes defined in block' do assert_recognizes({ controller: 'products', action: 'commit' }, '/products/commit') assert '/products/commit', commit_products_path end it 'must have overriden `new` path name' do assert_recognizes({ controller: 'products', action: 'new' }, '/products/make') assert '/products/make', new_product_path end it 'must have `wizardry_resources` helper' do with_routing do |set| set.draw{ wizardry_resources :products } assert_recognizes({ controller: 'products', action: 'edit', id: '1', step: 'initial'}, '/products/1/edit/initial') end end it 'must have `wizardry_resource` helper' do with_routing do |set| set.draw{ wizardry_resource :products } assert_recognizes({ controller: 'products', action: 'edit', step: 'initial'}, '/products/edit/initial') end end it 'must not let to use `has_wizardry` outside resource(s) scope' do with_routing do |set| assert_raises ArgumentError do set.draw{ has_wizardry } end end end it 'must not accept default `edit` route with `only` option' do with_routing do |set| set.draw{ wizardry_resources :products, only: [:edit, :update] } assert_raises ActionController::RoutingError do assert_recognizes({ controller: 'products', action: 'edit', id: '1'}, '/products/1/edit') end end end end
lexmag/wizardry
lib/wizardry.rb
<reponame>lexmag/wizardry<filename>lib/wizardry.rb require 'wizardry/version' require 'wizardry/base' require 'wizardry/routes' module Wizardry ORDINALS = %w[first second third fourth fifth sixth seventh] end
lexmag/wizardry
spec/wizardry/base_spec.rb
<gh_stars>1-10 require 'spec_helper' describe Wizardry::Base do describe 'class methods' do it 'must support `wizardry` method' do assert_respond_to Product, :wizardry end it 'must have steps array' do assert_equal Product.steps, %w[initial middle final] end it 'must have steps regexp' do assert_equal Product.steps_regexp, /initial|middle|final/ end it 'must be instance of StringInquirer class in steps array' do assert_equal Product.steps.map{ |s| s.instance_of?(ActiveSupport::StringInquirer) }, [true, true, true] end end describe 'instance methods' do before do @product = Product.new end it 'must return current step as first step' do assert_equal @product.current_step, 'initial' end it 'must update current step name with instance of StringInquirer' do @product.current_step = 'middle' assert_equal @product.current_step, 'middle' assert_instance_of ActiveSupport::StringInquirer, @product.current_step end it 'must update current step name when symbol is passed' do @product.current_step = :middle assert_equal @product.current_step, 'middle' end it 'must not update current step name' do @product.current_step = :fictional refute_equal @product.current_step, 'fictional' end it 'must have ordinal methods' do assert_equal @product.first_step, 'initial' assert_equal @product.second_step, 'middle' assert_equal @product.last_step, 'final' assert @product.first_step? refute @product.second_step? @product.current_step = :middle refute @product.first_step? assert @product.second_step? assert_respond_to @product, :last_step? refute_respond_to @product, :third_step refute_respond_to @product, :third_step? end it 'must return next step name' do assert_equal @product.next_step, 'middle' end it 'must return `nil` on last step' do @product.current_step = :final assert_nil @product.next_step end it 'must return `nil` on first step' do assert_nil @product.previous_step end it 'must return previous step name' do @product.current_step = :middle assert_equal @product.previous_step, 'initial' end it 'must return translated name of step' do assert_equal @product.step_title(:middle), 'Upload images' end it 'must return translated name of current step if no step passed' do assert_equal @product.step_title, 'Product details' @product.current_step = :middle assert_equal @product.step_title, 'Upload images' end it 'must fall back to default name of step' do assert_equal @product.step_title(:final), 'Final' assert_equal @product.step_title('final'), 'Final' end it 'must return `nil` for nonexistent step name' do assert_nil @product.step_title(:fictional) end end end
lexmag/wizardry
wizardry.gemspec
<gh_stars>1-10 require File.expand_path('../lib/wizardry/version', __FILE__) Gem::Specification.new do |gem| gem.authors = ['<NAME>'] gem.email = ['<EMAIL>'] gem.description = gem.summary = "Simple step-by-step wizard for Rails" gem.homepage = '' gem.files = `git ls-files`.split($\) gem.executables = gem.files.grep(%r{^bin/}).map{ |f| File.basename(f) } gem.test_files = gem.files.grep(%r{^spec/}) gem.name = 'wizardry' gem.require_paths = ['lib'] gem.version = Wizardry::VERSION gem.add_dependency 'rails', '~> 3.2' gem.add_development_dependency 'rake' gem.add_development_dependency 'sqlite3' gem.add_development_dependency 'minitest', '~> 4.7' end
lexmag/wizardry
lib/wizardry/routes.rb
<reponame>lexmag/wizardry class ActionDispatch::Routing::Mapper def has_wizardry unless resource_scope? raise ArgumentError, "can't use has_wizardry outside resource(s) scope" end options = @scope[:scope_level_resource].options if options.has_key?(:only) only = Array.wrap(options.delete(:only)) only.map!(&:to_sym).delete(:edit) options.merge!(only: only) if only.present? end except = Array.wrap(options.delete(:except)) except.map!(&:to_sym) << :edit options.merge!(except: except.uniq) res = @scope[:scope_level_resource].instance_variable_get(:@name) get 'edit/:step' => :edit, step: res.to_s.classify.constantize.steps_regexp, as: :edit, on: :member end [:resources, :resource].each do |method| class_eval <<-EOT, __FILE__, __LINE__ + 1 def wizardry_#{method}(*res) # def wizardry_resources(*res) #{method} *res do # resources *res do has_wizardry # has_wizardry yield if block_given? # yield if block_given? end # end end # end EOT end end
cpfergus1/rails-sales-taxes-kata-advanced
spec/features/baskets/user_baskets_page_spec.rb
# frozen_string_literal: true require 'rails_helper' RSpec.feature 'Baskets Index Page' do describe 'When I visit my baskets page' do let(:user) { create(:user, :with_baskets) } let(:other_user) { create(:user, :with_baskets) } before do sign_in(user) visit baskets_path(user) end it 'should have a list of all of my baskets' do expect(page).to have_selector('.basket-row', count: user.baskets.count) end it 'should not see other users baskets' do other_user.baskets.each do |basket| expect(page).to_not have_selector('.basket-row', text: basket.name) end end it 'should delete a basket if I click on the "Delete" link' do user_basket_count = user.baskets.count find('.basket-row', match: :first).click_link('Delete') expect(user.baskets.count).to eq(user_basket_count - 1) expect(page).to have_selector('.basket-row', count: user_basket_count - 1) end end describe 'When I visit the baskets page when not logged in' do it 'will redirect me to the log in page' do visit baskets_path expect(current_path).to eq(new_user_session_path) end end end
cpfergus1/rails-sales-taxes-kata-advanced
spec/models/line_item_spec.rb
<reponame>cpfergus1/rails-sales-taxes-kata-advanced # frozen_string_literal: true RSpec.describe LineItem do describe 'validations' do it do should validate_numericality_of(:price).is_greater_than(0) should validate_numericality_of(:quantity).is_greater_than(-1) end end describe 'relationships' do it { should belong_to(:basket).optional } end describe 'set_category' do let(:basket) { create(:basket) } it 'should set item_category column for LineItem before saving' do line_item = BasketReader.line_item('1 book at 12.49') expect(line_item.item_category).to eq(nil) basket.line_items << line_item expect(line_item.item_category.name).to eq('Book') end end end
cpfergus1/rails-sales-taxes-kata-advanced
app/models/baskets/receipt.rb
<gh_stars>0 # frozen_string_literal: true module Baskets class Receipt attr_reader :sales_tax, :total, :line_items def initialize(basket) @basket = basket @sales_tax = 0.0 @total = 0.0 @line_items = receipt_line_items end def print_sales_tax "Sales Taxes: #{'%.2f' % @sales_tax}" end def print_total "Total: #{'%.2f' % @total}" end def add_to_total(price) @total += price end def add_to_taxes(taxes) @sales_tax += taxes end def adjusted_item_price(item) taxes = Taxes.new(item).calculated_taxes add_to_taxes(taxes) taxes + item.price end def receipt_line_items @basket.line_items.map do |item| adjusted_price = adjusted_item_price(item) add_to_total(adjusted_price) "#{item.quantity} #{item.description}: #{'%.2f' % adjusted_price}" end end end end
cpfergus1/rails-sales-taxes-kata-advanced
app/models/taxes.rb
<reponame>cpfergus1/rails-sales-taxes-kata-advanced # frozen_string_literal: true class Taxes def initialize(item) @item = item end def applicable_tax (standard_tax + import_tax).round(2) end def standard_tax @item.item_category.name == "Others" ? 0.1 : 0 end def import_tax @item.description.downcase.include?("imported") ? 0.05 : 0 end def calculated_taxes ((applicable_tax * @item.price * @item.quantity * 20).ceil / 20.00).round(2) end end
cpfergus1/rails-sales-taxes-kata-advanced
spec/features/baskets/basket_receipt_spec.rb
# frozen_string_literal: true RSpec.describe 'Basket Show Page', type: :feature do describe "when I try to visit another user's basket receipt" do let(:user) { create(:user) } let(:other_user) { create(:basket, :with_items).user } before(:each) { sign_in(user) } it 'should return me to the main page', :vcr do visit basket_path(other_user.baskets.first) expect(current_path).to eq(root_path) end end end
cpfergus1/rails-sales-taxes-kata-advanced
spec/features/baskets/create_basket_spec.rb
# frozen_string_literal: true require 'rails_helper' RSpec.describe 'Basket Creation Page', type: :feature do let(:user) { create(:user) } before { sign_in(user) } describe 'I upload basket 2 list and click create' do it 'redirects me to the Basket show page with an itemized receipt' do visit new_basket_path attach_file('basket[basket_file]', file_fixture('basket_2.txt')) click_button('Create') expect(page).to have_content('10.50') expect(page).to have_content('54.65') expect(page).to have_content('7.65') expect(page).to have_content('65.15') end end describe 'I upload basket 1 list and click create' do it 'redirects me to the Basket show page with an itemized receipt' do visit new_basket_path attach_file('basket[basket_file]', file_fixture('basket_1.txt')) click_button('Create') expect(page).to have_content('12.49') expect(page).to have_content('16.49') expect(page).to have_content('0.85') expect(page).to have_content('1.50') expect(page).to have_content('29.83') end end describe 'I upload basket 3 list and click create' do it 'redirects me to the Basket show page with an itemized receipt' do visit new_basket_path attach_file('basket[basket_file]', file_fixture('basket_3.txt')) click_button('Create') expect(page).to have_content('32.19') expect(page).to have_content('20.89') expect(page).to have_content('9.75') expect(page).to have_content('11.85') expect(page).to have_content('6.70') expect(page).to have_content('74.68') end end describe 'I upload basket 4 with an invalid item in the list and click create' do it 'redirects me to the Basket create page with errors displayed' do visit new_basket_path attach_file('basket[basket_file]', file_fixture('basket_4.txt')) click_button('Create') expect(current_path).to eq(new_basket_path) expect(page).to have_content('Line items is invalid') end end describe 'I attempt to upload an invalid file format' do it 'redirects me to the Basket create page with errors displayed' do visit new_basket_path attach_file('basket[basket_file]', file_fixture('basket.csv')) click_button('Create') expect(current_path).to eq(new_basket_path) expect(page).to have_content('File type not allowed') end end describe 'I attempt to create a basket without uploading a file' do it 'redirects me to the Basket create page with errors displayed' do visit new_basket_path click_button('Create') expect(current_path).to eq(new_basket_path) expect(page).to have_content('Please select a file to upload') end end end
cpfergus1/rails-sales-taxes-kata-advanced
spec/factories/basket_factory.rb
<gh_stars>0 # frozen_string_literal: true FactoryBot.define do factory :basket do sequence(:name) { |n| "basket #{n}" } user trait :with_items do after(:create) do |basket| FactoryBot.create_list(:line_item, 4, basket: basket) end end trait :with_static_items do after(:create) do |basket| FactoryBot.create(:line_item, tax_free: true, price: 10, quantity: 1, basket: basket) FactoryBot.create(:line_item, taxable: true, price: 10, quantity: 1, basket: basket) FactoryBot.create(:line_item, taxable: true, imported: true, price: 10, quantity: 1, basket: basket) FactoryBot.create(:line_item, tax_free: true, imported: true, price: 10, quantity: 1, basket: basket) end end end end
cpfergus1/rails-sales-taxes-kata-advanced
app/controllers/baskets_controller.rb
<gh_stars>0 # frozen_string_literal: true class BasketsController < ApplicationController before_action :authenticate_user! before_action :correct_user, only: [:show, :destroy] before_action :check_no_file, :check_file_type, only: [:create] def index @baskets = current_user.baskets.order(created_at: :desc) end def destroy @basket = Basket.find(params[:id]) @basket.destroy flash[:alert] = "Basket was successfully deleted." redirect_to baskets_path end def show @basket = Basket.find(params[:id]) @receipt = Baskets::Receipt.new(@basket) end def new @basket = Basket.new end def create @basket = current_user.baskets.new(basket_params.except(:basket_file)) @basket.add_items(basket_params[:basket_file]) if @basket.save redirect_to basket_path(@basket.id) else flash[:error] = @basket.errors.full_messages.map(&:to_s).join(', ') redirect_to new_basket_url end end private def basket_params params.require(:basket).permit(:name, :basket_file) end def correct_user @basket = current_user.baskets.find_by(id: params[:id]) redirect_to root_url if @basket.nil? end def check_no_file if basket_params[:basket_file].nil? flash[:error] = 'Please select a file to upload.' redirect_to new_basket_path end end def check_file_type if BasketReader.file_type_not_allowed?(basket_params[:basket_file]) flash[:error] = 'File type not allowed.' redirect_to new_basket_path end end end
cpfergus1/rails-sales-taxes-kata-advanced
app/helpers/application_helper.rb
# frozen_string_literal: true require 'net/http' module ApplicationHelper def full_title(page_title = '') base_title = 'Basket Reader App' if page_title.empty? base_title else "#{page_title} | #{base_title}" end end end
cpfergus1/rails-sales-taxes-kata-advanced
app/models/item_category.rb
# frozen_string_literal: true class ItemCategory < ApplicationRecord has_many :line_items, dependent: :destroy end
cpfergus1/rails-sales-taxes-kata-advanced
spec/models/taxes_spec.rb
# frozen_string_literal: true RSpec.describe Taxes do let(:taxable_imported_line_item) { create(:line_item, price: 10, quantity: 1, taxable: true, imported: true) } let(:taxfree_imported_line_item) { create(:line_item, price: 10, quantity: 1, tax_free: true, imported: true) } let(:taxfree_line_item) { create(:line_item, price: 10, quantity: 1, tax_free: true) } let(:taxable_line_item) { create(:line_item, price: 10, quantity: 1, taxable: true) } describe 'initialize' do let(:line_item) { create(:line_item) } it 'should create a new Taxes instance' do expect(Taxes.new(line_item)).to be_a(Taxes) end end describe 'standard_tax' do it "should return tax only if the item is taxable" do expect(Taxes.new(taxable_line_item).standard_tax).to eq(0.1) expect(Taxes.new(taxfree_line_item).standard_tax).to eq(0) expect(Taxes.new(taxfree_imported_line_item).standard_tax).to eq(0) expect(Taxes.new(taxable_imported_line_item).standard_tax).to eq(0.1) end end describe 'imported_tax' do it "should return import tax only if the item is imported" do expect(Taxes.new(taxable_imported_line_item).import_tax).to eq(0.05) expect(Taxes.new(taxfree_imported_line_item).import_tax).to eq(0.05) expect(Taxes.new(taxable_line_item).import_tax).to eq(0) expect(Taxes.new(taxfree_line_item).import_tax).to eq(0) end end describe 'applicable_tax' do it "should return the sum of the applied taxes" do expect(Taxes.new(taxable_imported_line_item).applicable_tax).to eq(0.15) expect(Taxes.new(taxfree_imported_line_item).applicable_tax).to eq(0.05) expect(Taxes.new(taxable_line_item).applicable_tax).to eq(0.1) expect(Taxes.new(taxfree_line_item).applicable_tax).to eq(0) end end describe 'calculated_taxes' do it "should return the product of the taxes, item quantity and price" do expect(Taxes.new(taxable_imported_line_item).calculated_taxes).to eq(1.50) expect(Taxes.new(taxfree_imported_line_item).calculated_taxes).to eq(0.50) expect(Taxes.new(taxable_line_item).calculated_taxes).to eq(1.00) expect(Taxes.new(taxfree_line_item).calculated_taxes).to eq(0.00) end end end
cpfergus1/rails-sales-taxes-kata-advanced
app/controllers/static_pages_controller.rb
# frozen_string_literal: true class StaticPagesController < ApplicationController def welcome end end
cpfergus1/rails-sales-taxes-kata-advanced
app/models/line_item.rb
<filename>app/models/line_item.rb # frozen_string_literal: true class LineItem < ApplicationRecord before_validation :set_category belongs_to :basket, optional: true belongs_to :item_category validates :quantity, numericality: { only_integer: true, greater_than: -1 } validates :price, numericality: { greater_than: 0 } private def set_category return if item_category.present? self.item_category = LineItem.select { |line_item| description&.include?(line_item.description) }&.first&.item_category end end
cpfergus1/rails-sales-taxes-kata-advanced
db/migrate/20210812124129_add_item_category_references_to_line_items.rb
<filename>db/migrate/20210812124129_add_item_category_references_to_line_items.rb class AddItemCategoryReferencesToLineItems < ActiveRecord::Migration[6.1] def change remove_column :line_items, :item_category add_reference :line_items, :item_category, null: false, foreign_key: true end end
cpfergus1/rails-sales-taxes-kata-advanced
app/services/cat_image_service.rb
# frozen_string_literal: true class CatImageService def self.get_image JSON.parse(request.body)[0]['url'] end def self.query params = { size: 'med' } uri = URI('https://api.thecatapi.com/v1/images/search') uri.query = URI.encode_www_form(params) uri end def self.header request = Net::HTTP::Get.new(query) request['x-api-key'] = ENV['CAT_API_KEY'] request end def self.request Net::HTTP.start(query.hostname, query.port, use_ssl: true) do |http| http.request(header) end end end
cpfergus1/rails-sales-taxes-kata-advanced
db/migrate/20210811191841_create_line_items.rb
class CreateLineItems < ActiveRecord::Migration[6.1] def change create_table :line_items do |t| t.string :description t.integer :quantity t.float :price t.string :item_category t.references :basket, null: false, foreign_key: true t.timestamps end end end
cpfergus1/rails-sales-taxes-kata-advanced
config/routes.rb
<filename>config/routes.rb # frozen_string_literal: true Rails.application.routes.draw do get 'baskets/index' devise_for :users resources :baskets, except: [:update, :edit] root 'static_pages#welcome' # For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html end
cpfergus1/rails-sales-taxes-kata-advanced
db/seeds.rb
# frozen_string_literal: true # 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 bin/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) categories = ['Medicine', 'Book', 'Food', 'Others'] categories.each do |category| ItemCategory.find_or_create_by(name: category) end line_item_descriptions = {'book' => 'Book', 'music CD' => 'Others', 'chocolate' => 'Food', 'perfume' => 'Others', 'pills' => 'Medicine' } line_item_descriptions.each do |line_item_description, category| LineItem.find_or_create_by(description: line_item_description, item_category: ItemCategory.find_by(name: category), price: 1, quantity: 1) end
cpfergus1/rails-sales-taxes-kata-advanced
spec/models/baskets/receipt_spec.rb
# frozen_string_literal: true RSpec.describe Baskets::Receipt do let(:basket) { create(:basket, :with_static_items) } subject(:receipt) { described_class.new(basket) } describe 'initialize' do it 'should create a new Receipt object' do expect(receipt).to be_a(Baskets::Receipt) end end describe 'adjusted_item_price' do let(:taxable_line_item) { create(:line_item, price: 10, quantity: 1, taxable: true) } let(:tax_free_line_item) { create(:line_item, price: 10, quantity: 1, tax_free: true) } let(:tax_free_imported_line_item) { create(:line_item, price: 10, quantity: 1, tax_free: true, imported: true) } let(:taxable_imported_line_item) { create(:line_item, price: 10, quantity: 1, taxable: true, imported: true) } it 'should return the adjusted_item_price after tax' do expect(receipt.adjusted_item_price(taxable_line_item)).to eq(11.00) expect(receipt.adjusted_item_price(tax_free_line_item)).to eq(10.00) expect(receipt.adjusted_item_price(taxable_imported_line_item)).to eq(11.50) expect(receipt.adjusted_item_price(tax_free_imported_line_item)).to eq(10.50) end end describe 'receipt_line_items' do it 'returns and array of formatted line item strings' do expect(receipt.receipt_line_items.count).to eq(4) expect(receipt.receipt_line_items).to be_a(Array) expect(receipt.receipt_line_items.first).to be_a(String) expect(receipt.receipt_line_items.first).to be_a(String) expect(receipt.receipt_line_items.first).to match(/^[1-9]{1,} [a-zA-z]*: [0-9]*.[0-9]{2}\z/) end end describe 'print_sales_tax' do it 'returns the formatted sales tax amount' do expect(receipt.print_sales_tax).to be_a(String) expect(receipt.print_sales_tax).to match(/^[a-zA-z]* [a-zA-z]*: [0-9]*.[0-9]{2}\z/) expect(receipt.sales_tax).to eq(3) end end describe 'print_total' do it 'returns the formated basket total amount' do expect(receipt.print_total).to be_a(String) expect(receipt.print_total).to match(/^[a-zA-z]*: [0-9]*.[0-9]{2}\z/) expect(receipt.total).to eq(43.00) end end end
cpfergus1/rails-sales-taxes-kata-advanced
app/models/basket.rb
<filename>app/models/basket.rb<gh_stars>0 # frozen_string_literal: true class Basket < ApplicationRecord belongs_to :user has_many :line_items, dependent: :destroy def add_items(file) BasketReader.read_basket(file).each do |line_item| line_items << line_item end end end
cpfergus1/rails-sales-taxes-kata-advanced
spec/factories/line_item_factory.rb
# frozen_string_literal: true FactoryBot.define do factory :line_item do transient do imported { false } taxable { false } tax_free { false } end description { ['book', 'box of chocolates', 'headache pills', 'bottle of perfume'].sample } quantity { rand(1..10) } price { rand(1.00..10.00) } basket before(:create) do |line_item, evaluator| line_item.description = 'bottle of perfume' if evaluator.taxable line_item.description = 'book' if evaluator.tax_free line_item.description << ' imported' if evaluator.imported end end end
cpfergus1/rails-sales-taxes-kata-advanced
spec/helpers/basket_reader_spec.rb
# frozen_string_literal: true RSpec.describe 'BasketReader' do describe 'self.line_item' do it 'builds a LineItem from parsed text' do item_text = '1 book at 12.49' item = BasketReader.line_item(item_text) expect(item.description).to eq('book') expect(item.quantity).to eq(1) expect(item.price).to eq(12.49) end end describe 'self.parse_items' do let(:file) { file_fixture('basket_1.txt').read.split(/\n/) } it 'parses a string of items into a list of LineItems' do line_items = BasketReader.parse_items(file) expect(line_items.size).to eq(3) end end describe 'self.read_basket' do let(:file) { file_fixture('basket_1.txt') } it 'reads a file and returns an array of line items' do line_items = BasketReader.read_basket(file) expect(line_items.size).to eq(3) expect(line_items.class).to eq(Array) expect(line_items.first.class).to eq(LineItem) end end end
cpfergus1/rails-sales-taxes-kata-advanced
spec/features/static_pages/welcome_spec.rb
<reponame>cpfergus1/rails-sales-taxes-kata-advanced # frozen_string_literal: true require 'rails_helper' RSpec.feature 'Welcome Page' do describe 'The welcome landing page', :vcr do describe 'When not logged in' do it 'Has welcome page and login elements' do visit root_path expect(page).to have_content('Welcome to the Basket Reader App') expect(page).to have_link("Log in", href: new_user_session_path) expect(page).to have_link("Sign up now!", href: new_user_registration_path) expect(page).to have_link("Home", href: root_path) expect(page).to_not have_link("Account") expect(page).to_not have_link("My Baskets") end end describe 'When logged in' do let(:user) { FactoryBot.create(:user) } before { sign_in(user) } it 'Links change to user dropdown menus and basket links elements' do visit root_path expect(page).to have_link('Account', href: '#') expect(page).to have_link('Log out', href: destroy_user_session_path) expect(page).to have_link('Profile', href: edit_user_registration_path(user.id)) expect(page).to have_link('My Baskets', href: baskets_path) expect(page).to_not have_link("Log in", href: new_user_session_path) expect(page).to_not have_link("Sign up now!", href: new_user_registration_path) end end it 'cat picture should be randomized each visit' do visit root_path expect(page).to have_selector('img[alt="cat"]') first_image = find("//img[@alt='cat']")['src'] visit root_path second_image = find("//img[@alt='cat']")['src'] expect(first_image).to_not eq(second_image) end end end
cpfergus1/rails-sales-taxes-kata-advanced
app/helpers/basket_reader.rb
# frozen_string_literal: true # frozen_string_literal: true class BasketReader def self.file_type_not_allowed?(file) file.content_type != 'text/plain' end def self.read_basket(basket) basket_contents = File.read(basket).split("\n") parse_items(basket_contents) end def self.parse_items(basket_contents) basket_contents.map do |item| line_item(item) end end def self.line_item(item) quantity = item[0] price = item.partition(' at ').last description = item.partition(' at ').first[2..] LineItem.new(description: description, quantity: quantity, price: price) end end
cpfergus1/rails-sales-taxes-kata-advanced
db/migrate/20210812141827_remove_null_flag_from_line_items.rb
class RemoveNullFlagFromLineItems < ActiveRecord::Migration[6.1] def change change_column_null :line_items, :basket_id, true end end
cpfergus1/rails-sales-taxes-kata-advanced
spec/services/cat_image_service_spec.rb
<gh_stars>0 # frozen_string_literal: true require 'rails_helper' RSpec.describe CatImageService do it 'fetches an image of a cat', :vcr do expect(CatImageService.get_image).to match(/https:\/\/cdn2.thecatapi.com\/images\/.*/) end end
Rainiugnas/password_manager
lib/cli.rb
<filename>lib/cli.rb # frozen_string_literal: true require 'password_manager' require 'cli/input' require 'cli/option' require 'cli/storage' # Handle actions related to the cli interface. module Cli # Raise a password manager exception with the given message # @param message [String] Error message # @raise [PasswordManager::PasswordManagerError] Exception raise def self.interupt! message; raise PasswordManager::PasswordManagerError, message end # Starter point of the cli. # Run Cli.run, it use the ARGV arguments to find and execute an action. # Catch all PasswordManager::PasswordManagerError to stop the execution and print the error. def self.run option = success! Option.new storage = success!(Storage.new option.file) password = <PASSWORD>!(Input::PasswordConfirmation.new "Enter your password: \n") crypters = [ PasswordManager::Crypter::Aes.new(password.value), PasswordManager::Crypter::Base64.new ] send find_action(option), storage, crypters, option rescue PasswordManager::PasswordManagerError => e print e.message end # Check that the given object have true success and return the object. # @param [Object] object Object to check, must respond to success and error method # @raise [PasswordManager::PasswordManagerError] When success is false def self.success! object return object if object.success interupt! object.error end # Print in std out the data of the given site # @param [Site] site def self.display_site site puts "Data associated to #{site.name}:" puts "- username: #{site.user}" puts "- password: #{site.password}" end # @!group Actions # Encrypt the file (json -> crypted) # @param storage [Storage] Hold and handle the data of the given file # @param crypters [Arrays(Crypter)] Crypters to encrypt / decrypt the data # @param _option [Option] Parsed ARGV arguments def self.encrypt storage, crypters, _option storage.data = PasswordManager::Converter.from_json(storage.data, crypters).to_crypt storage.save! end # Decrypt the file (crypted -> json) # @param storage [Storage] Hold and handle the data of the given file # @param crypters [Arrays(Crypter)] Crypters to encrypt / decrypt the data # @param _option [Option] Parsed ARGV argumentss def self.decrypt storage, crypters, _option storage.data = PasswordManager::Converter.from_crypt(storage.data, crypters).to_json storage.save! end # List all site name (crypted -> crypted) # @param storage [Storage] Hold and handle the data of the given file # @param crypters [Arrays(Crypter)] Crypters to encrypt / decrypt the data # @param _option [Option] Parsed ARGV arguments def self.list storage, crypters, _option sites = PasswordManager::Converter.from_crypt(storage.data, crypters).to_array puts "Found #{sites.count} sites names:" sites.each { |site| puts site.name } end # Find the the site and display it's data (crypted -> crypted) # @param storage [Storage] Hold and handle the data of the given file # @param crypters [Arrays(Crypter)] Crypters to encrypt / decrypt the data # @param option [Option] Parsed ARGV arguments, hold the site to find def self.show storage, crypters, option sites = PasswordManager::Converter.from_crypt(storage.data, crypters).to_array target = sites.select { |site| site.name == option.show }.try :first interupt! "Error: '#{option.show}' is not a valid site name" if target.nil? display_site target end # As the user to enter site data and save it (crypted -> crypted) # @param storage [Storage] Hold and handle the data of the given file # @param crypters [Arrays(Crypter)] Crypters to encrypt / decrypt the data # @param _option [Option] Parsed ARGV arguments def self.add storage, crypters, _option site = success! Input::Site.new converter = PasswordManager::Converter.from_crypt storage.data, crypters converter = PasswordManager::Converter.from_array(converter.to_array + [site], crypters) storage.data = converter.to_crypt storage.save! end # Decrypt the file and wait for input, then encrypt the file (crypted -> crypted) # @param storage [Storage] Hold and handle the data of the given file # @param crypters [Arrays(Crypter)] Crypters to encrypt / decrypt the data # @param _option [Option] Parsed ARGV arguments def self.tmp storage, crypters, _option decrypt storage, crypters, nil Input::Stop.new "Press enter to continue.\n" storage.reload encrypt storage, crypters, nil end # Find the option action to execute (encrypt, decrypt, add, show, list, tmp) # @param option [Option] Hold the action to execute from ARGV def self.find_action option %i(encrypt decrypt add show list tmp).each do |action| return action if option.send action end end private_class_method :find_action, :encrypt, :decrypt, :add, :show, :list, :tmp, :success!, :display_site end
Rainiugnas/password_manager
lib/cli/input/site.rb
<filename>lib/cli/input/site.rb # frozen_string_literal: true module Cli module Input # Model to retrieve site data from the input class Site < PasswordManager::Site # Build the site with the data from the input def initialize super ask_site_name!, ask_user_name!, Password.new("password: \n").value end private # Ask for the site name and return the result # @return [String] def ask_site_name! puts 'sitename: ' STDIN.gets.chomp end # Ask for the user name and return the result # @return [String] def ask_user_name! puts 'username: ' STDIN.gets.chomp end end end end
Rainiugnas/password_manager
spec/lib/password_manager/crypter/base64_spec.rb
# frozen_string_literal: true RSpec.describe Base64 do let(:crypter) { PasswordManager::Crypter::Base64.new } let(:data) { 'data' } let(:encrypted_data) { crypter.encrypt data } describe 'interface' do it 'should implement crypter interface' do expect(crypter).to be_crypter end end describe '#encrypt' do it 'should encrypt the given data' do expect(encrypted_data).not_to eq data end end describe '#decrypt' do it 'should be able to decrypt encrypted data' do expect(crypter.decrypt encrypted_data).to eq data end end end
Rainiugnas/password_manager
lib/password_manager/converter.rb
# frozen_string_literal: true module PasswordManager # Convert data between several format (site array, json, encrypted) # Use the given crypters to encrypt / decrypt. # # Converter is build from formated data, # parse and store the data and can be re-use to re-format the data # # Encrypting apply the first crypter and apply the next one. # Decrypting apply the last crypter and apply the previous one. # @private @attr [Array(Site)] data All the site from the given data # @private @attr [Array(Crypter)] crypters Store the crypters to apply class Converter # @!group From # Build the converter from crypted data # @param data [String] Encrypted data # @param crypters [Array(Crypter)] Crypters to use to encrypt / decrypt # @return [Converter] Converter with the site array from the given data def self.from_crypt data, crypters crypters.reverse_each { |crypter| data = crypter.decrypt data } Converter.from_json data, crypters end # Build the converter from json data # @param data [String] Json data # @param crypters [Array(Crypter)] Crypters to use to encrypt / decrypt # @raise [ConverterError] When the data have json formating error # @return [Converter] Converter with the site array from the given data def self.from_json data, crypters data = [].tap do |result| sites = JSON.parse data sites.each do |name, values| extra = values.except 'username', 'password' result.push Site.new name, values['username'], values['password'], extra end end Converter.from_array data, crypters rescue JSON::ParserError raise ConverterError, 'Error: the json provided is invalid' end # Build the converter from site array # @param data [Array(Site)] Site to convert # @param crypters [Array(Crypter)] Crypters to use to encrypt / decrypt # @return [Converter] Converter with the site array from the given data def self.from_array data, crypters; Converter.new data, crypters end # @!endgroup # @deprecated Use {.from_array} instead def initialize data, crypters @crypters = crypters @data = data end # @!group To # @return [Site(Array)] The raw site array def to_array; @data.freeze end # @return [String] The data formated into json string def to_json hash = {}.tap do |result| to_array.each do |site| result[site.name] = site.extra.merge 'username' => site.user, 'password' => site.password end end JSON.generate hash end # @return [String] The data formatted in to encrypted string def to_crypt data = to_json @crypters.each { |crypter| data = crypter.encrypt data } data end end end
Rainiugnas/password_manager
lib/password_manager/crypter.rb
<filename>lib/password_manager/crypter.rb # frozen_string_literal: true require_relative 'crypter/aes' require_relative 'crypter/base64' module PasswordManager # Namespace which contains all crypter classes. # A crypter have an encrypt and decrypt method use to format data. module Crypter end end
Rainiugnas/password_manager
lib/password_manager/crypter/base64.rb
<reponame>Rainiugnas/password_manager<gh_stars>0 # frozen_string_literal: true module PasswordManager module Crypter # Handle Base64 format class Base64 # @param [String] data Data to encrypt # @return [String] the Base64 encrypted data def encrypt(data) ::Base64.encode64 data end # @param [String] data Base64 data to decrypt # @return [String] Result of the decryption def decrypt(data) ::Base64.decode64 data end end end end
Rainiugnas/password_manager
password_manager.gemspec
# frozen_string_literal: true lib = File.expand_path('lib', __dir__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'password_manager/version' Gem::Specification.new do |spec| spec.name = 'password_manager' spec.version = PasswordManager::VERSION spec.authors = ['Rainiugnas'] spec.email = ['<EMAIL>'] spec.summary = 'Handle encryption of json data which contains web site passwords.' spec.license = 'MIT' spec.files = `git ls-files -z`.split("\x0").reject do |f| f.match(%r{^(test|spec|features)/}) end spec.bindir = 'bin/exe' spec.executables = spec.files.grep(%r{^bin/exe/}) { |f| File.basename(f) } spec.require_paths = ['lib'] # DEPENDENCIES # Tools # Monkey patch basic classes like Hash, Array, ... to add extra methods spec.add_runtime_dependency 'activesupport', '~> 5.1.6' end
Rainiugnas/password_manager
lib/cli/input/password.rb
<reponame>Rainiugnas/password_manager<gh_stars>0 # frozen_string_literal: true module Cli module Input # Model to retrieve password data from the input # @attr_reader [String] value The password from input # @attr_reader [String] error Alway nil # @attr_reader [Boolean] success Alway true class Password attr_reader :value, :error, :success # Ask the password with the given message. # @param [String] message The message displayed to ask the password def initialize message @value = ask! message @success = true end private # Ask the password with the given message and return the result # @param [String] message # @return [String] def ask! message print message STDIN.noecho(&:gets).chomp end end end end
Rainiugnas/password_manager
lib/password_manager/exceptions.rb
# frozen_string_literal: true module PasswordManager # Global exception class throw by password manager class PasswordManagerError < RuntimeError; end # Throw by crypter when the decrypt fail class DecryptError < PasswordManagerError; end # Throw by crypter when the encrypt fail class EncryptError < PasswordManagerError; end # Throw by converter when the convertion fail class ConverterError < PasswordManagerError; end end
Rainiugnas/password_manager
spec/lib/cli_spec.rb
# frozen_string_literal: true # rubocop:disable Metrics/BlockLength RSpec.describe Cli do describe '.interupt!' do it 'should raise an password manager exception with the given message' do expect { Cli.interupt! 'message' }.to raise_exception 'message' end end describe '.run' do let(:site1) { PasswordManager::Site.new '1', 'user', 'password' } let(:site2) { PasswordManager::Site.new '2', 'user', 'password' } let(:site3) { PasswordManager::Site.new '3', 'user', 'password' } let(:sites) { [site1, site2, site3] } let(:crypter1) { Aes.new password } let(:crypter2) { PasswordManager::Crypter::Base64.new } let(:crypters) { [crypter1, crypter2] } let(:converter) { Converter.from_array sites, crypters } let(:json_file) { converter.to_json } let(:crypt_file) { converter.to_crypt } let(:readable?) { true } let(:path) { 'file/path' } let(:file) { crypt_file } let(:password) { 'password' } let(:password_error) { '<PASSWORD>' } let(:password_success?) { true } before(:each) do allow(File).to receive(:read).with(path).and_return file allow(File).to receive(:readable?).and_return readable? allow(File).to receive(:writable?).and_return true dummy_password = double(value: password, success: password_success?, error: password_error) allow(PasswordConfirmation).to receive(:new).and_return dummy_password stub_const 'ARGV', %w(rspec).concat(argv) end describe 'storage error' do let(:readable?) { false } let(:argv) { %w(-e -f).push path } it 'should print the error' do message = 'Error: the given file have not read and write right' expect { Cli.run }.to output(message).to_stdout end end describe 'option error' do let(:argv) { %w(-e -d -f).push path } it 'should print the error' do message = <<~MSG invalid option: you must set one (no more) of the following options: --encrypt, --decrypt, --show, --add, --tmp and --list MSG expect { Cli.run }.to output(message).to_stdout end end describe 'password error' do let(:argv) { %w(-e -f).push path } let(:password_success?) { false } it 'should print the error' do expect { Cli.run }.to output(password_error).to_stdout end end describe 'encrypt' do let(:argv) { %w(-e -f).push path } let(:file) { json_file } it 'should encrypt the file' do expect(File).to receive(:write).with path, crypt_file Cli.run end end describe 'decrypt' do let(:argv) { %w(-d -f).push path } let(:file) { crypt_file } it 'should decrypt the file' do expect(File).to receive(:write).with path, json_file Cli.run end end describe 'list' do let(:argv) { %w(-l -f).push path } let(:file) { crypt_file } it 'should list the name of all the file site' do message = <<~MSG Found 3 sites names: 1 2 3 MSG expect { Cli.run }.to output(message).to_stdout end end describe 'add' do let(:argv) { %w(-a -f).push path } let(:file) { crypt_file } let(:new_site) { PasswordManager::Site.new '4', 'user', 'password' } it 'should add the new site to the file' do expect(Cli::Input::Site).to receive(:new).and_return new_site udpdated_converter = Converter.from_array(converter.to_array + [new_site], crypters) expect(File).to receive(:write).with(path, udpdated_converter.to_crypt) Cli.run end context 'when the site is invalid' do let(:new_site) { PasswordManager::Site.new '', 'user', 'password' } it 'should print the error' do expect(Cli::Input::Site).to receive(:new).and_return new_site expect { Cli.run }.to output('Error: site name must be present').to_stdout end end end describe 'show' do let(:argv) { %w(-s 2 -f).push path } let(:file) { crypt_file } it 'should find the site and display the data' do message = <<~MSG Data associated to 2: - username: user - password: password MSG expect { Cli.run }.to output(message).to_stdout end context 'when the site does not exist' do let(:argv) { %w(-s unknow -f).push path } it 'should print the error' do message = "Error: 'unknow' is not a valid site name" expect { Cli.run }.to output(message).to_stdout end end end describe 'tmp' do let(:argv) { %w(-t -f).push path } it 'should decrypt the file and after the stop re encrypt it' do expect(File).to receive(:read).with(path).and_return crypt_file expect(File).to receive(:write).with path, json_file expect(Stop).to receive(:new) expect(File).to receive(:read).with(path).and_return json_file expect(File).to receive(:write).with path, crypt_file Cli.run end end end end
Rainiugnas/password_manager
spec/lib/cli/storage_spec.rb
<reponame>Rainiugnas/password_manager<filename>spec/lib/cli/storage_spec.rb # frozen_string_literal: true # rubocop:disable Metrics/BlockLength RSpec.describe Storage do let(:path) { '/path' } let(:readable?) { true } let(:writable?) { true } let(:data) { 'data' } let(:storage) { Storage.new path } before(:each) do allow(File).to receive(:read).with(path).and_return data allow(File).to receive(:readable?).and_return readable? allow(File).to receive(:writable?).and_return writable? end describe '.new' do context 'with readable and writeable file' do it 'should success and set the storage data' do expect(storage.success).to be_truthy expect(storage.data).to eq data end end context 'when file is not readable' do let(:readable?) { false } it 'should not success and set an error' do expect(storage.success).to be_falsy expect(storage.error).to eq 'Error: the given file have not read and write right' end end context 'when file is not writeable' do let(:writable?) { false } it 'should not success and set an error' do expect(storage.success).to be_falsy expect(storage.error).to eq 'Error: the given file have not read and write right' end end end describe 'reload' do it 'should read the file data and set the value' do old_data = storage.data expect(File).to receive(:read).with(path).and_return 'new data' storage.reload expect(storage.data).not_to eq old_data expect(storage.data).to eq 'new data' end end describe 'save!' do it 'should write the storage data into the file' do expect(File).to receive(:write).with(path, data) storage.save! end end end
Rainiugnas/password_manager
spec/lib/password_manager/crypter/aes_spec.rb
<reponame>Rainiugnas/password_manager # frozen_string_literal: true # rubocop:disable Metrics/BlockLength RSpec.describe Aes do let(:aes_1) { Aes.new '1' } let(:aes_2) { Aes.new '2' } let(:data) { 'data' } let(:encrypted_data) { aes_1.encrypt data } describe 'interface' do it 'should implement crypter interface' do expect(aes_1).to be_crypter end end describe '#encrypt' do it 'should encrypt the given data' do expect(encrypted_data).not_to eq data end it 'should use the given password to encrypt the data' do expect(encrypted_data).not_to eq aes_2.encrypt data end end describe '#decrypt' do context 'when password is the same than encrypt' do it 'should be able to decrypt encrypted data' do expect(aes_1.decrypt encrypted_data).to eq data end end context 'when password is not the same than encrypt' do it 'should raise an exception' do expect { aes_2.decrypt encrypted_data }.to raise_exception DecryptError end end end end
Rainiugnas/password_manager
lib/cli_file_crypter.rb
# frozen_string_literal: true require 'cli' # Handle actions related to the cli file crypter interface. module CliFileCrypter # Starter point of the cli file crypter. # Run CliFileCrypter.run, it use the ARGV arguments to find and execute an action. # Catch all PasswordManager::PasswordManagerError to stop the execution and print the error. def self.run option = success! Cli::Option.new storage = success!(Cli::Storage.new option.file) password = success!(Cli::Input::PasswordConfirmation.new "Enter your password: \n") crypters = [ PasswordManager::Crypter::Aes.new(password.value), PasswordManager::Crypter::Base64.new ] send find_action(option), storage, crypters, option rescue PasswordManager::PasswordManagerError => e print e.message end # Raise a password manager exception with the given message # @param message [String] Error message # @raise [PasswordManager::PasswordManagerError] Exception raise def self.interupt! message; raise PasswordManager::PasswordManagerError, message end # Check that the given object have true success and return the object. # @param [Object] object Object to check, must respond to success and error method # @raise [PasswordManager::PasswordManagerError] When success is false def self.success! object return object if object.success interupt! object.error end # @!group Actions # Encrypt the file # @param storage [Storage] Hold and handle the data of the given file # @param crypters [Arrays(Crypter)] Crypters to encrypt / decrypt the data # @param _option [Option] Parsed ARGV arguments def self.encrypt storage, crypters, _option crypters.each { |crypter| storage.data = crypter.encrypt storage.data } storage.save! end # Decrypt the file # @param storage [Storage] Hold and handle the data of the given file # @param crypters [Arrays(Crypter)] Crypters to encrypt / decrypt the data # @param _option [Option] Parsed ARGV argumentss def self.decrypt storage, crypters, _option crypters.reverse_each { |crypter| storage.data = crypter.decrypt storage.data } storage.save! end # Find the option action to execute (encrypt or decrypt) # @param option [Option] Hold the action to execute from ARGV def self.find_action option %i(encrypt decrypt).each do |action| return action if option.send action end interupt! 'Option must be file and either encrypt or decrypt. Other option are not suported.' end private_class_method :find_action, :encrypt, :decrypt, :success! end
Rainiugnas/password_manager
spec/lib/cli/option_spec.rb
<reponame>Rainiugnas/password_manager # frozen_string_literal: true # rubocop:disable Metrics/BlockLength RSpec.describe Option do shared_examples :set_option do |argv_options, option_name, expected_value| context "with #{argv_options.join(' ')}" do let(:argv) { argv_options } it "should set the option #{option_name}" do expect(option.send option_name).to eq expected_value end end end let(:option) { Option.new } before :each do stub_const 'ARGV', %w(rspec).concat(argv) end describe 'options' do include_examples :set_option, %w(-f path), :file, 'path' include_examples :set_option, %w(--file path), :file, 'path' include_examples :set_option, %w(-e), :encrypt, true include_examples :set_option, %w(--encrypt), :encrypt, true include_examples :set_option, %w(-d), :decrypt, true include_examples :set_option, %w(--decrypt), :decrypt, true include_examples :set_option, %w(-s site), :show, 'site' include_examples :set_option, %w(--show site), :show, 'site' include_examples :set_option, %w(-l), :list, true include_examples :set_option, %w(--list), :list, true include_examples :set_option, %w(-a), :add, true include_examples :set_option, %w(--add), :add, true include_examples :set_option, %w(-t), :tmp, true include_examples :set_option, %w(--tmp), :tmp, true context 'without argv' do let(:argv) { [] } it 'should set the options to their default value' do expect(option.file).to be_nil expect(option.show).to be_nil expect(option.file).to be_falsy expect(option.encrypt).to be_falsy expect(option.decrypt).to be_falsy expect(option.list).to be_falsy expect(option.add).to be_falsy expect(option.tmp).to be_falsy end end end describe 'errors' do context 'with an unknow option' do let(:argv) { %w(--unknow -f path -d) } it 'should not success' do expect(option.success).to be_falsy expect(option.error).to match /invalid option: --unknow/ end end context 'with --help' do let(:argv) { %w(--help -f path -d) } it 'should not success and hold the help message' do expect(option.success).to be_falsy expect(option.error).to match /Usage:/ end end context 'without file path' do let(:argv) { %w(-d) } it 'should not success' do expect(option.success).to be_falsy expect(option.error).to eq 'invalid option: file (option -f / --file) must be provided' end end context 'without any actions option' do let(:argv) { %w(-f path) } it 'should not success' do expect(option.success).to be_falsy expect(option.error).to eq <<~MSG invalid option: you must set one (no more) of the following options: --encrypt, --decrypt, --show, --add, --tmp and --list MSG end end context 'with more than one action options' do let(:argv) { %w(-f path -d -t) } it 'should not success' do expect(option.success).to be_falsy expect(option.error).to eq <<~MSG invalid option: you must set one (no more) of the following options: --encrypt, --decrypt, --show, --add, --tmp and --list MSG end end end describe 'success' do context 'with valid option' do let(:argv) { %w(-f path -t) } it 'should success' do expect(option.success).to be_truthy end end end end
Rainiugnas/password_manager
lib/cli/input.rb
# frozen_string_literal: true require_relative 'input/password' require_relative 'input/password_confirmation' require_relative 'input/site' require_relative 'input/stop' module Cli # Namespace which contains all input classes. # Input classe will ask for std_in interaction at initialization. module Input end end