Skip to content

Commit

Permalink
add specs
Browse files Browse the repository at this point in the history
  • Loading branch information
tycooon committed Feb 3, 2019
1 parent 10bde3a commit 135c2a0
Show file tree
Hide file tree
Showing 3 changed files with 107 additions and 9 deletions.
20 changes: 11 additions & 9 deletions lib/polist/struct.rb
Original file line number Diff line number Diff line change
Expand Up @@ -2,17 +2,19 @@

module Polist
module Struct
def self.struct(receiver, *attrs)
instance_method(:struct).bind(receiver).call(*attrs)
end

def struct(*attrs)
attr_accessor(*attrs)
module ClassMethods
def struct(*attrs)
attr_accessor(*attrs)

define_method(:initialize) do |*args|
raise ArgumentError, "struct size differs" if args.length > attrs.length
attrs.zip(args).each { |attr, val| public_send(:"#{attr}=", val) }
define_method(:initialize) do |*args|
raise ArgumentError, "struct size differs" if args.length > attrs.length
attrs.zip(args).each { |attr, val| public_send(:"#{attr}=", val) }
end
end
end

def self.included(base)
base.extend(ClassMethods)
end
end
end
67 changes: 67 additions & 0 deletions spec/polist/builder_spec.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
# frozen_string_literal: true

class User
include Polist::Builder

builds do |role|
case role
when /admin/
Admin
end
end

attr_accessor :role

def initialize(role)
self.role = role
end
end

class Admin < User
builds do |role|
role == "super_admin" ? SuperAdmin : Admin
end

class SuperAdmin < self
def super?
true
end
end

def super?
false
end
end

RSpec.describe Polist::Builder do
let(:user) { User.build(role) }

context "user role" do
let(:role) { "user" }

it "builds user" do
expect(user.class).to eq(User)
expect(user.role).to eq("user")
end
end

context "admin role" do
let(:role) { "admin" }

it "builds admin" do
expect(user.class).to eq(Admin)
expect(user.role).to eq("admin")
expect(user.super?).to eq(false)
end
end

context "super_admin role" do
let(:role) { "super_admin" }

it "builds super_admin" do
expect(user.class).to eq(Admin::SuperAdmin)
expect(user.role).to eq("super_admin")
expect(user.super?).to eq(true)
end
end
end
29 changes: 29 additions & 0 deletions spec/polist/struct_spec.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
# frozen_string_literal: true

class Point
include Polist::Struct

struct :x, :y
end

RSpec.describe Polist::Struct do
specify "basic usage" do
a = Point.new(15, 25)
expect(a.x).to eq(15)
expect(a.y).to eq(25)
end

context "too many arguments" do
it "raises exception" do
expect { Point.new(15, 25, 35) }.to raise_error(ArgumentError, "struct size differs")
end
end

context "only 1 argument" do
it "defaults to nil" do
a = Point.new(15)
expect(a.x).to eq(15)
expect(a.y).to eq(nil)
end
end
end

0 comments on commit 135c2a0

Please sign in to comment.