module OutputAttributes

This module creates a class helper method ‘output` that can be used to create an output configuration The goal is to help assemble a class’s hash representation.

Each time you call ‘output` in the class definition, you register a key => proc pair. You can then call `#output_attributes` to get the hash of key => values

Example:

class Item
  include OutputAttributes

  # You can register outputs similar to attr_accessors
  output :name

  def name
    "A Thing"
  end

  # Since the `def meth` expression returns a symbol, you can also register it like a decorator.
  # It returns the symbol so you could keep chaining with other similar tools like memoize
  output def price
    "free"
  end

  # You can rename a method/key:
  output :cost, from: :price

  # You can also define a custom proc if the key doesn't match a method name.
  # The argument to your proc is the instance itself so you have easy access to it's methods
  output :description, from: ->(item){ [item.name, item.price].join(': ') }

  # You can also call whatever you want:
  output :extracted_at, from: ->(_){ Time.now }

  def a_helper_method
    "Ignore this"
  end

  # It does not override `#to_h/ash`, but this is easy enough if you wish!
  def to_h
    output_attributes
  end
  alias to_hash output_attributes
end

item = Item.new
item.output_attributes || item.to_h || item.to_hash
# => 
  {
    name: "A Thing",
    price: "Free",
    description: "A Thing: Free",
    extracted_at: 2019-11-26 14:33:00.000
  }

Constants

VERSION

Public Class Methods

included(base) click to toggle source

Register this class’s catalog of outputs

# File lib/output_attributes.rb, line 60
def self.included(base)
  base.class_eval do
    @registered_output_attributes = {}

    def self.output(key, from: nil)
      @registered_output_attributes[key] = from || key
      key
    end

    def self.registered_output_attributes
      @registered_output_attributes
    end
  end
end
output(key, from: nil) click to toggle source
# File lib/output_attributes.rb, line 64
def self.output(key, from: nil)
  @registered_output_attributes[key] = from || key
  key
end
registered_output_attributes() click to toggle source
# File lib/output_attributes.rb, line 69
def self.registered_output_attributes
  @registered_output_attributes
end

Public Instance Methods

output_attributes() click to toggle source

Return a hash representing your outputs

# File lib/output_attributes.rb, line 76
def output_attributes
  self.class.registered_output_attributes.map do |key, meth|
    value = case meth
    when Symbol, String
      self.send(meth.to_sym)
    when Proc
      meth.call(self)
    else
      raise ArgumentError, "Could not determine how to output #{meth} for #{key}."
    end
    [key, value]
  end.to_h
end