lib/banditry.rb in banditry-0.4.0 vs lib/banditry.rb in banditry-0.5.0

- old
+ new

@@ -1,7 +1,10 @@ +# frozen-string-literal: true + require 'banditry/version' require 'banditry/bandit_mask' +require 'forwardable' module Banditry class BanditryError < StandardError end @@ -47,48 +50,59 @@ # file.mode_mask # => 3 # file.mode = [:r, :x] # file.mode_mask # => 5 def bandit_mask(attribute, as:, with: BanditMask) class_eval do + extend SingleForwardable + + generate_class_method as, with generate_reader attribute, as, with generate_writer attribute, as, with generate_query attribute, as, with end end private - def generate_reader(attr, virt, cls) + def generate_class_method(virt, bandit) respond_to? virt and - raise MethodCollisionError, "method `#{virt}` already exists" + raise MethodCollisionError, "method `#{self}.#{virt}` already exists" - define_method virt do - instance_variable_get(:"@#{virt}") || - instance_variable_set(:"@#{virt}", cls.new(send(attr))) + def_single_delegator bandit, :bits, virt + end + + def generate_reader(attr, virt, bandit) + instance_methods.include? virt and + raise MethodCollisionError, "method `#{self}##{virt}` already exists" + + define_method virt do |reload = false| + reload = true if !instance_variable_defined? :"@#{virt}" + instance_variable_set :"@#{virt}", bandit.new(send(attr)) if reload + instance_variable_get :"@#{virt}" end end - def generate_writer(attr, virt, cls) - respond_to? :"#{virt}=" and - raise MethodCollisionError, "method `#{virt}=` already exists" + def generate_writer(attr, virt, bandit) + instance_methods.include? :"#{virt}=" and + raise MethodCollisionError, "method `#{self}##{virt}=` already exists" define_method :"#{virt}=" do |bits| mask = case bits when BanditMask bits else - bits.inject(cls.new) { |bm, bit| bm << bit } + bits.inject(bandit.new) { |bm, bit| bm << bit } end send :"#{attr}=", Integer(mask) instance_variable_set :"@#{virt}", mask end end - def generate_query(attr, virt, cls) - respond_to? :"#{virt}?" and - raise MethodCollisionError, "method `#{virt}?` already exists" + def generate_query(attr, virt, bandit) + instance_methods.include? :"#{virt}?" and + raise MethodCollisionError, "method `#{self}##{virt}?` already exists" define_method :"#{virt}?" do |*bits| - cls.new(send(attr)).include? *bits + bandit.new(send(attr)).include?(*bits) end end end