diff --git a/HISTORY.md b/HISTORY.md index bc2c29a2..74c142f3 100644 --- a/HISTORY.md +++ b/HISTORY.md @@ -18,6 +18,11 @@ Changes: first, back into a number: `[1, 0].from_base(256)` is 256. It reverses Ruby's `Integer#digits`, as `n.digits(b).reverse.from_base(b)`. All three load with `require 'facets'`, and are based on the Radix gem. + * `String#margin` takes a `:flush` option, which gives every line the + same margin and doesn't keep their relative indentation: + `"abc\n xyz".margin(2, flush: true)` is `" abc\n xyz"`. This is + what `String#tab`, removed in 3.1.0, used to do; `String#tabto` is + `margin(n, lead: true)`. * `Mirror`, loaded with `require 'facets/mirror'`, looks at an object from the outside: `obj.mirror.to_h` gives its instance variables as a hash, and the mirror also gets and sets them, and gives the object's @@ -26,6 +31,22 @@ Changes: `instance_variables`, or a `BasicObject` that has neither. The class is `Kernel::Mirror`, so an application's own `Mirror` class takes precedence instead of clashing. Based on the Instance gem. + * `Paramix::Parametric`, loaded with `require 'facets/paramix'`, makes a + module take parameters where it is included or extended: + `include Greeter[:name => 'x']`. The module's `parameterized` block is + given the parameters and defines the methods that depend on them. + Paramix was part of Facets until 2.7.0; this is the Paramix gem's + version. + * `String::Mask` and `String#mask`, loaded with + `require 'facets/string/mask'`, treat a string as a mask with empty + slots and combine masks character by character: + `("abc..123".mask('.') + "ab..789.").to_s` is `"abc.7893"`, and `-`, + `*`, `&` and `^` work likewise. This was Facets' `string/mask` until + 2.7.0, then the Strmask gem. Compared with the gem: masks of + different lengths can be combined, a mask can be made without an + empty-slot character, equal masks are the same hash key, `apply` + works, only methods a string has are passed on to it, and a mask is + equal only to another mask (compare `mask.to_s` with a string). * Bug fixes diff --git a/lib/core/facets/string.rb b/lib/core/facets/string.rb index c7a76a3b..001e1ab4 100644 --- a/lib/core/facets/string.rb +++ b/lib/core/facets/string.rb @@ -25,6 +25,7 @@ require_relative 'string/linear.rb' require_relative 'string/lowercase.rb' require_relative 'string/margin.rb' +#require_relative 'string/mask.rb' # uncommon require_relative 'string/methodize.rb' require_relative 'string/modulize.rb' require_relative 'string/mscan.rb' diff --git a/lib/core/facets/string/margin.rb b/lib/core/facets/string/margin.rb index fbfaac68..0f464dce 100644 --- a/lib/core/facets/string/margin.rb +++ b/lib/core/facets/string/margin.rb @@ -14,6 +14,17 @@ class String # by the first non-blank line, instead of the minimum white-space for all # lines. # + # " abc\n xyz".margin(0) #=> "abc\n xyz" + # " abc\n xyz".margin(2, lead: true) #=> " abc\nxyz" + # + # If the `:flush` option is set, relative tabbing is not preserved: every + # line that isn't blank gets exactly the given number of spaces before + # non-space, whatever spaces or tabs it started with. Blank lines are + # left as they are. + # + # "abc\n xyz".margin(2) #=> " abc\n xyz" + # "abc\n xyz".margin(2, flush: true) #=> " abc\n xyz" + # # Arguments: # # num - The size of the desired margin. [Integer] @@ -21,8 +32,9 @@ class String # # Options: # - # :tab - Size of tab character in spaces. [Integer] - # :lead - Use first non-blank line as relative marker. [Boolean] + # :tab - Size of tab character in spaces. [Integer] + # :lead - Use first non-blank line as relative marker. [Boolean] + # :flush - Give every line the same margin. [Boolean] # # Returns a new String with adjusted margin. [String] # @@ -33,6 +45,8 @@ def margin(num=nil, opts={}) # TODO: temporary to help people transition raise ArgumentError, "String#margin has been renamed to #trim." unless num + return gsub(/^[ \t]*(?=\S)/, ' ' * num) if opts[:flush] + tab = opts[:tab] || 2 str = gsub("\t", " " * tab) # TODO: only leading tabs ? diff --git a/lib/core/facets/string/mask.rb b/lib/core/facets/string/mask.rb new file mode 100644 index 00000000..1e696648 --- /dev/null +++ b/lib/core/facets/string/mask.rb @@ -0,0 +1,264 @@ +class String + + # Make a mask of the string, in which each `re` is an empty slot. + # See String::Mask. + # + # m = "abc..123".mask('.') + # (m + "ab..789.").to_s #=> "abc.7893" + # + # re - The character that marks an empty slot. [String] + # + # Returns a new mask. [String::Mask] + # + # @uncommon + # require 'facets/string/mask' + # + # Since: 4.2.0 + + def mask(re=nil) + Mask.new(self, re) + end + + # A Mask is a string in which some characters are empty slots. Masks + # of the same length combine character by character, with operators + # that work like those of sets or bits. + # + # m1 = String::Mask.new("abc..123", '.') + # m2 = "ab..789.".mask('.') + # + # (m1 + m2).to_s #=> "abc.7893" + # (m1 - m2).to_s #=> "....789." + # (m1 & m2).to_s #=> "ab......" + # (m1 ^ m2).to_s #=> "..c.7..3" + # + # The second operand can be an ordinary string, which is read as a + # mask with the same empty-slot character as the first. + # + # ("abc..123".mask('.') + "ab..789.").to_s #=> "abc.7893" + # + # Where one mask is shorter than the other, its missing characters + # count as empty slots. + # + # Without an empty-slot character, the ASCII substitute character + # (`"\x1A"`, Mask::ESC) marks an empty slot. That is the better choice + # when "." or any other printable character might be part of the text. + # + # Methods a mask doesn't have are passed to its string, so + # `mask.size` and `mask.upcase` work as they do for a string. + # + # Based on the Strmask gem, which began as Facets' `string/mask`. + # + # Since: 4.2.0 + # Author: Trans + + class Mask + + # The character that stands for an empty slot inside a mask: ASCII + # substitute. + ESC = "\032" + + # Make a mask. Same as Mask.new. + # + # Returns a new mask. [String::Mask] + def self.[](string, re=nil) + new(string, re) + end + + # string - Any string, or the string of another mask. [String] + # re - The character that marks an empty slot. [String] + def initialize(string, re=nil) + @to_str = string.to_str.dup + @re = re || ESC + mask!(re) if re + end + + # The underlying string, in which ESC marks each empty slot. + # + # Returns the string. [String] + def to_str + @to_str + end + + # The mask as an ordinary string, with the empty-slot character it + # was made with. + # + # Returns a new string. [String] + def to_s + @to_str.gsub(ESC, @re) + end + + # + def inspect + to_s.inspect + end + + # Index into the underlying string. + def [](*a) + to_str[*a] + end + + # A mask of the same underlying string with another empty-slot + # character. + # + # re - The character that marks an empty slot. [String] + # + # Returns a new mask. [String::Mask] + def mask(re) + self.class.new(to_str, re) + end + + # Turn each `re` in this mask into an empty slot. + # + # Returns this mask. [String::Mask] + def mask!(re) + to_str.gsub!(re){ |s| ESC * s.size } + self + end + + # Mask subtraction. Where the characters are the same, the result is + # empty; where they differ, the result is the other's. + # + # a = "abc..123".mask('.') + # b = "ab..789.".mask('.') + # + # (a - b).to_s #=> "....789." + # (b - a).to_s #=> "..c..123" + # + def -(other) + combine(other){ |a, b| a == b ? ESC : b } + end + + # Mask addition. The other's character comes through unless it is + # empty, in which case this mask's does. + # + # a = "abc..123".mask('.') + # b = "ab..789.".mask('.') + # + # (a + b).to_s #=> "abc.7893" + # (b + a).to_s #=> "abc.7123" + # + def +(other) + combine(other){ |a, b| b == ESC ? a : b } + end + + # Mask OR is the same as addition. + alias_method :|, :+ + + # Mask XAND. Where the characters are the same, the result is the + # same; where they differ, the result is the other's. + # + # a = "abc..123".mask('.') + # b = "ab..789.".mask('.') + # + # (a * b).to_s #=> "ab..789." + # (b * a).to_s #=> "abc..123" + # + def *(other) + combine(other){ |a, b| a == b ? a : b } + end + + # Mask AND. Only characters that are the same come through. + # + # a = "abc..123".mask('.') + # b = "ab..789.".mask('.') + # + # (a & b).to_s #=> "ab......" + # (b & a).to_s #=> "ab......" + # + def &(other) + combine(other){ |a, b| a == b ? a : ESC } + end + + # Mask XOR. A character comes through only where the other mask has + # an empty slot. + # + # a = "abc..123".mask('.') + # b = "ab..789.".mask('.') + # + # (a ^ b).to_s #=> "..c.7..3" + # (b ^ a).to_s #=> "..c.7..3" + # + def ^(other) + combine(other) do |a, b| + if a == ESC then b + elsif b == ESC then a + else ESC + end + end + end + + # Masks are equal if they have the same characters and the same + # empty slots, whatever character each was made with. A mask is + # never equal to an ordinary string: compare its `to_s` instead. + # + # m = "abc..123".mask('.') + # + # (m == "abc__123".mask('_')) #=> true + # (m == "abc..123") #=> false + # (m.to_s == "abc..123") #=> true + # + def ==(other) + Mask === other && to_str == other.to_str + end + + alias_method :eql?, :== + + # + def hash + to_str.hash + end + + # Call a method on the underlying string and make a mask of the + # result. + # + # "abc..123".mask('.').apply(:upcase).to_s #=> "ABC..123" + # + # Returns a new mask. [String::Mask] + def apply(op, *a, &b) + self.class.new(to_str.public_send(op, *a, &b), @re) + end + + # Replace the underlying string. + # + # Returns this mask. [String::Mask] + def replace(string) + @to_str = string.to_s.dup + self + end + + # Pass any other method to the underlying string. + def method_missing(s, *a, &b) + if to_str.respond_to?(s) + to_str.public_send(s, *a, &b) + else + super + end + end + + # + def respond_to_missing?(s, include_all=false) + to_str.respond_to?(s) || super + end + + private + + # Read anything that isn't a mask as one with this mask's empty-slot + # character. + def convert(other) + Mask === other ? other : self.class.new(other.to_str, @re) + end + + # A new mask made by giving the block each pair of characters, with + # ESC standing in past the end of the shorter mask. + def combine(other) + other = convert(other).to_str + out = String.new(encoding: to_str.encoding) + [to_str.size, other.size].max.times do |i| + out << yield(to_str[i] || ESC, other[i] || ESC) + end + self.class.new(out, @re) + end + + end + +end diff --git a/lib/standard/facets/paramix.rb b/lib/standard/facets/paramix.rb new file mode 100644 index 00000000..c930c4ee --- /dev/null +++ b/lib/standard/facets/paramix.rb @@ -0,0 +1,153 @@ +# Paramix namespace. +# +# NOTE: This is not loaded by `require 'facets'`. Use: +# +# require 'facets/paramix' +# +# Based on the Paramix gem. +# +# Since: 4.2.0 +# Author: Trans + +module Paramix + + # A parametric mixin is a module that takes parameters where it is + # included or extended, with `Module[parameters]`. Its `parameterized` + # block is given the parameters, and defines the methods that depend + # on them. + # + # module Greeter + # include Paramix::Parametric + # + # parameterized do |params| + # define_method :hello do + # "Hello from #{params[:name]}!" + # end + # end + # end + # + # class English + # include Greeter[:name => 'England'] + # end + # + # class Scots + # include Greeter[:name => 'Scotland'] + # end + # + # English.new.hello #=> "Hello from England!" + # Scots.new.hello #=> "Hello from Scotland!" + # + # Each use of `Module[parameters]` makes a new module that includes the + # parametric one, so each class gets its own methods. The block runs in + # that module, where `public`, `private` and `protected` also define a + # method when given a block: + # + # module Named + # include Paramix::Parametric + # + # parameterized do |params| + # public(params[:as]) { params[:value] } + # end + # end + # + # class Config + # extend Named[:as => :env, :value => 'test'] + # end + # + # Config.env #=> "test" + # + # A module that includes a parametric module without giving it + # parameters becomes parametric too, and passes its own parameters on. + + module Parametric + + # + def self.included(base) + base.extend(Extensions) + end + + # Class-level methods of a parametric module. + module Extensions + + # Apply parameters, giving a module to include or extend. + # + # Returns a new Mixin. [Mixin] + def [](parameters={}) + Mixin.new(self, parameters) + end + + # Add a block to run when parameters are applied. Without a block, + # gives the blocks added so far. + # + # Returns the list of blocks. [Array] + def parameterized(&code) + @code ||= [] + if block_given? + @code << code + else + @code + end + end + + # + def append_features(base) + return super(base) if Mixin === base || Mixin === self + + base.extend(Extensions) + + anc = ancestors.find{ |a| a.respond_to?(:parameterized) } + base.parameterized.concat(anc.parameterized) + + super(base) + end + + # + def extend_object(base) + return super(base) if Mixin === base || Mixin === self + + base.extend(Extensions) + + anc = ancestors.find{ |a| a.respond_to?(:parameterized) } + base.parameterized.concat(anc.parameterized) + + super(base) + end + + end + + # An instance of the Mixin module class is what is produced + # when parameters are applied to a parametric module. + # + class Mixin < Module + + def initialize(base, parameters) + super() + include(base) + base.parameterized.each do |code| + instance_exec(parameters, &code) + end + end + + # As Module#public, and given a block, define the method first. + def public(*names, &code) + define_method(names.first, &code) if code + super(*names) + end + + # As Module#private, and given a block, define the method first. + def private(*names, &code) + define_method(names.first, &code) if code + super(*names) + end + + # As Module#protected, and given a block, define the method first. + def protected(*names, &code) + define_method(names.first, &code) if code + super(*names) + end + + end + + end + +end diff --git a/test/core/string/test_margin.rb b/test/core/string/test_margin.rb index d082df95..0d4060a0 100644 --- a/test/core/string/test_margin.rb +++ b/test/core/string/test_margin.rb @@ -2,7 +2,6 @@ test_case String do - # TODO: Need to expand margin tests method :margin do test do @@ -10,7 +9,50 @@ a[0..3].assert == ' ' end + test "moves the least indented line to the margin" do + " abc\n xyz".margin(0).assert == "abc\n xyz" + "abc\n xyz".margin(2).assert == " abc\n xyz" + " abc\n xyz".margin(1).assert == " abc\n xyz" + end + + test "ignores blank lines when finding the least indented line" do + " abc\n\n xyz".margin(2).assert == " abc\n\n xyz" + end + + test "counts a tab as two spaces, or as the :tab option says" do + "\tabc".margin(0).assert == "abc" + "\tabc\n xyz".margin(1).assert == " abc\n xyz" + "\tabc\n xyz".margin(0, :tab => 4).assert == " abc\nxyz" + end + + test "with :lead, moves the first line that isn't blank to the margin" do + " abc\n xyz".margin(2, :lead => true).assert == " abc\n xyz" + " abc\n xyz".margin(2, :lead => true).assert == " abc\nxyz" + end + + test "with :flush, gives every line the same margin" do + "abc\n xyz".margin(2, :flush => true).assert == " abc\n xyz" + " abc\n xyz".margin(0, :flush => true).assert == "abc\nxyz" + end + + test "with :flush, treats leading tabs as indentation" do + "\tabc\n \t xyz".margin(2, :flush => true).assert == " abc\n xyz" + end + + test "with :flush, leaves blank lines and the rest of each line alone" do + "abc def\n\n \n xyz\n".margin(2, :flush => true).assert == " abc def\n\n \n xyz\n" + end + + test "does not change the receiver" do + s = "abc\n xyz" + s.margin(2, :flush => true) + s.assert == "abc\n xyz" + end + + test "must be given a margin" do + ArgumentError.assert.raised? { "abc".margin } + end + end end - diff --git a/test/core/string/test_mask.rb b/test/core/string/test_mask.rb new file mode 100644 index 00000000..b519117f --- /dev/null +++ b/test/core/string/test_mask.rb @@ -0,0 +1,213 @@ +covers 'facets/string/mask' + +test_case String do + + method :mask do + + test "makes a mask with the given empty-slot character" do + m = "abc..123".mask('.') + m.assert.kind_of?(String::Mask) + m.assert == String::Mask.new("abc..123", '.') + end + + end + +end + +test_case String::Mask do + + x1 = String::Mask["abc..123", '.'] + x2 = String::Mask["ab..789.", '.'] + + class_method :[] do + + test "is the same as new" do + String::Mask["abc..123", '.'].assert == String::Mask.new("abc..123", '.') + end + + end + + method :+ do + + test "takes the other's character unless it is empty" do + (x1 + x2).to_s.assert == "abc.7893" + (x2 + x1).to_s.assert == "abc.7123" + end + + test "reads an ordinary string as a mask" do + (x1 + "ab..789.").to_s.assert == "abc.7893" + end + + test "counts characters past the end of the shorter mask as empty" do + ("abc".mask('.') + "..cde").to_s.assert == "abcde" + ("..cde".mask('.') + "abc").to_s.assert == "abcde" + end + + test "keeps the string's encoding" do + r = "héllo..".mask('.') + ".....!!" + r.to_s.assert == "héllo!!" + r.to_s.encoding.assert == Encoding::UTF_8 + end + + test "does not change either mask" do + a = String::Mask["abc..123", '.'] + a + x2 + a.to_s.assert == "abc..123" + end + + end + + method :| do + + test "is the same as +" do + (x1 | x2).assert == (x1 + x2) + end + + end + + method :- do + + test "is empty where the characters match, and the other's where they differ" do + (x1 - x2).to_s.assert == "....789." + (x2 - x1).to_s.assert == "..c..123" + end + + end + + method :* do + + test "keeps matching characters, and takes the other's where they differ" do + (x1 * x2).to_s.assert == "ab..789." + (x2 * x1).to_s.assert == "abc..123" + end + + end + + method :& do + + test "keeps only matching characters" do + (x1 & x2).to_s.assert == "ab......" + (x2 & x1).to_s.assert == "ab......" + end + + end + + method :^ do + + test "keeps a character only where the other is empty" do + (x1 ^ x2).to_s.assert == "..c.7..3" + (x2 ^ x1).to_s.assert == "..c.7..3" + end + + end + + method :== do + + test "is true for a mask with the same characters and empty slots" do + x1.assert == String::Mask["abc..123", '.'] + x1.refute == x2 + end + + test "is true for a mask made with another empty-slot character" do + x1.assert == String::Mask["abc__123", '_'] + end + + test "is false for an ordinary string, either way round" do + (x1 == "abc..123").assert == false + (x1 == x1.to_str).assert == false + ("abc..123" == x1).assert == false + (x1.to_s == "abc..123").assert == true + end + + test "is false for anything that isn't a string" do + (x1 == 5).assert == false + (x1 == nil).assert == false + end + + end + + method :hash do + + test "lets equal masks be the same hash key" do + h = { String::Mask["abc..123", '.'] => 1 } + h[String::Mask["abc..123", '.']].assert == 1 + h["abc..123"].assert == nil + end + + end + + method :to_s do + + test "gives the string with its empty-slot character" do + x1.to_s.assert == "abc..123" + x1.to_s.assert.instance_of?(String) + end + + test "uses the substitute character when none was given" do + m = String::Mask.new("ab\x1Ad") + m.to_s.assert == "ab\x1Ad" + (m + "..c.".mask('.')).to_s.assert == "abcd" + end + + end + + method :to_str do + + test "gives the underlying string, with ESC in each empty slot" do + x1.to_str.assert == "abc\x1A\x1A123" + end + + end + + method :mask do + + test "gives a mask of the same slots with another character" do + x1.mask('_').to_s.assert == "abc__123" + x1.to_s.assert == "abc..123" + end + + end + + method :apply do + + test "calls a method on the string and makes a mask of the result" do + m = x1.apply(:upcase) + m.assert.kind_of?(String::Mask) + m.to_s.assert == "ABC..123" + end + + end + + method :replace do + + test "replaces the underlying string" do + m = String::Mask["abc", '.'] + m.replace("xyz") + m.to_s.assert == "xyz" + end + + end + + method :method_missing do + + test "passes other methods to the string" do + x1.size.assert == 8 + x1.assert.respond_to?(:upcase) + end + + test "raises NoMethodError for a method a string doesn't have" do + NoMethodError.assert.raised? { x1.no_such_method } + x1.refute.respond_to?(:no_such_method) + end + + end + + method :inspect do + + test "is the inspection of the string" do + x1.inspect.assert == '"abc..123"' + end + + end + +end diff --git a/test/standard/test_paramix.rb b/test/standard/test_paramix.rb new file mode 100644 index 00000000..7f01fb7e --- /dev/null +++ b/test/standard/test_paramix.rb @@ -0,0 +1,142 @@ +covers 'facets/paramix' + +test_case Paramix::Parametric::Extensions do + + # A parametric module that defines the method named by :name, returning + # :value. + maker = lambda do + Module.new do + include Paramix::Parametric + parameterized do |params| + public(params[:name]) { params[:value] } + end + end + end + + method :parameterized do + + test "is added to a module that includes Parametric" do + m = maker.call + m.assert.respond_to?(:parameterized) + m.assert.respond_to?(:[]) + end + + end + + method :[] do + + test "parameters are given where the module is included" do + m = maker.call + c = Class.new { include m[:name => :f, :value => 1] } + c.new.f.assert == 1 + end + + test "each inclusion has its own parameters" do + m = maker.call + a = Class.new { include m[:name => :f, :value => 'a'] } + b = Class.new { include m[:name => :f, :value => 'b'] } + a.new.f.assert == 'a' + b.new.f.assert == 'b' + end + + test "parameters are given where the module is extended" do + m = maker.call + a = Class.new { extend m[:name => :f, :value => 'mosh'] } + b = Class.new { extend m[:name => :f, :value => 'many'] } + a.f.assert == 'mosh' + b.f.assert == 'many' + end + + test "the module's own methods come along" do + m = Module.new do + include Paramix::Parametric + parameterized do |params| + define_method(:params) { params } + end + def hello + "Hello, %s!" % [params[:name]] + end + end + c = Class.new { include m[:name => 'Charlie'] } + c.new.hello.assert == "Hello, Charlie!" + end + + test "the block can define any methods from its parameters" do + m = Module.new do + include Paramix::Parametric + parameterized do |params| + attr_accessor params[:p] + end + end + c = Class.new { include m[:p => :color] } + o = c.new + o.color = :red + o.color.assert == :red + end + + test "private and protected define methods with that visibility" do + m = Module.new do + include Paramix::Parametric + parameterized do |params| + private(:secret) { params[:value] } + protected(:guarded) { params[:value] } + public(:reveal) { secret } + end + end + c = Class.new { include m[:value => 42] } + c.new.reveal.assert == 42 + c.private_instance_methods.assert.include?(:secret) + c.protected_instance_methods.assert.include?(:guarded) + end + + test "public, private and protected still take names alone" do + m = Module.new do + include Paramix::Parametric + parameterized do |params| + define_method(:a) { 1 } + define_method(:b) { 2 } + private :a, :b + end + end + c = Class.new { include m[] } + c.private_instance_methods.assert.include?(:a) + c.private_instance_methods.assert.include?(:b) + end + + test "a parametric module can include another with parameters" do + inner = maker.call + outer = Module.new do + include Paramix::Parametric + include inner[:name => :f, :value => 1] + parameterized do |params| + public(params[:name]) { params[:value] } + end + end + c = Class.new { include outer[:name => :g, :value => 2] } + c.new.f.assert == 1 + c.new.g.assert == 2 + end + + test "a module that includes one without parameters becomes parametric" do + inner = maker.call + outer = Module.new do + include inner + parameterized do |params| + public(params[:name].to_s.succ) { params[:value] } + end + end + c = Class.new { include outer[:name => :q, :value => 3] } + c.new.q.assert == 3 + c.new.r.assert == 3 + end + + test "a plain module can pass a parameterized one on" do + inner = maker.call + plain = Module.new { include inner[:name => :f, :value => 'NMp'] } + Class.new { include plain }.new.f.assert == 'NMp' + Class.new { extend plain }.f.assert == 'NMp' + end + + end + +end