Last active
July 14, 2023 20:47
-
-
Save mrgenixus/d69bbc39cb73eb6f703f26123da8297c to your computer and use it in GitHub Desktop.
Formatter
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#consider using a 'formatter' collaborator and then using: | |
delegate :min_yardage, to: :formatter, prefix: formatted | |
# so that `formatted_min_yardage` returns the formatted value. | |
#A formatter might be a. PORO with a block passed to new line: | |
def formatter | |
@formatter = ModelFormatter.new(self) do | |
include ActionView/Helpers::NumberHelper | |
min_yardage :fmt_number | |
def fmt_number arg | |
number_with_delimiter(arg, ",") | |
end | |
end | |
end | |
class ModelFormatter | |
def initialize(model, &block) | |
@model = model | |
class_eval(&block) if block_given? | |
end | |
class << self | |
def method_missing method, *args, &block | |
@formatters[method] ||= {} | |
@formatters[method][:args] = [*(@formatters[method][:args]||[]), *args] | |
@formatters[method][:block] = block | |
end | |
end | |
def method_missing method *args, **options, &block | |
if method.starts_with('formatted') | |
(@formatters[method][:args]||[]).reduce(@model.send(method)) do |memo, op| | |
send(op, memo) | |
end.tap do |result| | |
end | |
else | |
@model.send(method, *args, **options) | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment