Sha256: f0a6284deb91f9a132e1f116783a9e95ca4c50187d8ec19992882021d4feefcc

Contents?: true

Size: 940 Bytes

Versions: 5

Compression:

Stored size: 940 Bytes

Contents

# frozen_string_literal: true

# 346325

module Wayfarer
  module Stringify
    def self.included(base)
      base.include(InstanceMethods)
      base.extend(ClassMethods)
      base.instance_eval do
        cattr_accessor :stringified_attributes do
          []
        end
      end
    end

    module ClassMethods
      def stringify(*variables)
        stringified_attributes.concat(variables)
      end
    end

    module InstanceMethods
      def to_s
        if self.class.stringified_attributes.any?
          "#<#{class_name} #{attributes.join(', ')}>"
        else
          "#<#{class_name}>"
        end
      end

      alias inspect to_s

      def class_name
        self.class.name
      end

      def attributes
        self.class
            .stringified_attributes
            .map { |attr| [attr, public_send(attr)] }
            .to_h
            .map { |k, v| [k, "=", v.inspect].join }
      end
    end
  end
end

Version data entries

5 entries across 5 versions & 1 rubygems

Version Path
wayfarer-0.4.6 lib/wayfarer/stringify.rb
wayfarer-0.4.5 lib/wayfarer/stringify.rb
wayfarer-0.4.4 lib/wayfarer/stringify.rb
wayfarer-0.4.3 lib/wayfarer/stringify.rb
wayfarer-0.4.2 lib/wayfarer/stringify.rb