Instantly share code, notes, and snippets.

Embed
What would you like to do?
how to include Enumerable in Rails in order to have `blank?` functionality
require 'active_support/core_ext/module/delegation'
require 'active_support/core_ext/object/blank'
require 'rspec'
class Membership
class MembershipCollection
include Enumerable
delegate :empty?, :each, to: :@members
def initialize(*members)
@members = members.flatten
end
def free
select { |m| m.free? }
end
def paid
select { |m| m.paid? }
end
end
attr_accessor :type
def free?
type == 'free'
end
def paid?
type == 'paid'
end
end
puts "\nMembership without state:"
m = Membership.new
puts m.free?
# => false
puts m.paid?
# => false
puts Membership::MembershipCollection.new(m).free.inspect
# => []
puts Membership::MembershipCollection.new(m).paid.inspect
# => []
puts "\nMembership with 'free' state:"
m.type = 'free'
puts m.free?
# => true
puts m.paid?
#=> false
puts Membership::MembershipCollection.new(m).free.inspect
# => [m]
puts Membership::MembershipCollection.new(m).paid.inspect
# => []
puts "\nMembership with 'paid' state:"
m.type = 'paid'
puts m.free?.inspect
# => false
m.paid?
# => true
puts Membership::MembershipCollection.new(m).free.inspect
# => []
puts Membership::MembershipCollection.new(m).paid.inspect
# => [m]
puts "\n\nRSpec test:"
RSpec.describe Membership::MembershipCollection do
subject { described_class.new(memberships) }
let(:free_membership) { Membership.new.tap { |m| m.type = 'free'} }
let(:paid_membership) { Membership.new.tap { |m| m.type = 'paid'} }
context 'when no memberships' do
let(:memberships) { [] }
it { expect(subject).to be_blank }
it { expect(subject).to be_empty }
it { expect(subject.free).to be_empty }
it { expect(subject.paid).to be_empty }
end
context 'when free memberships' do
let(:memberships) { [free_membership] }
it { expect(subject).not_to be_blank }
it { expect(subject).not_to be_empty }
it { expect(subject.free).to eq([free_membership]) }
it { expect(subject.paid).to be_empty }
end
context 'when paid memberships' do
let(:memberships) { [paid_membership] }
it { expect(subject).not_to be_blank }
it { expect(subject).not_to be_empty }
it { expect(subject.free).to be_empty }
it { expect(subject.paid).to eq([paid_membership]) }
end
end