Skip to content

Instantly share code, notes, and snippets.

@nwjsmith
Created September 26, 2011 16:28
Show Gist options
  • Save nwjsmith/1242659 to your computer and use it in GitHub Desktop.
Save nwjsmith/1242659 to your computer and use it in GitHub Desktop.
module Formattable
def format(opts)
# ...
end
end
class Basketball::PlayerRecord
extend Formattable
format :fields =>[:rebounds_total, :minutes, :assists, :points], :with => '-'
end
@lsantos
Copy link

lsantos commented Sep 27, 2011 via email

@lsantos
Copy link

lsantos commented Sep 27, 2011

To illustrate my idea, here is some more code exploring the method_missing, following a method protocol.

Advantage:

  • We don't have to call sleazy_formatter first, so you save some typing

Drawback:

  • We will have to override the active record method missing
module Formattable
  SUFFIX_PROTOCOL_RE = /_with$/ 

  def method_missing(method_sym, *args)
    original_method = extract_original_method(method_sym)
    return super unless follow_protocol?(method_sym, original_method)

    default_value = args.first
    actual_value = send(original_method)
    actual_value.nil? ? default_value : actual_value
  end

  def extract_original_method(method_sym)
    method_sym.to_s.gsub(SUFFIX_PROTOCOL_RE, '')
  end

  def follow_protocol?(calling_method, original_method)
    SUFFIX_PROTOCOL_RE.match(calling_method.to_s) && respond_to?(original_method)
  end

end

class Person
  include Formattable

  attr_reader :first_name, :last_name

  def initialize(first_name)
    @first_name = first_name
  end

end

p = Person.new("Thuva")
p.first_name # Thuva
p.last_name # nil
p.first_name # Thuva
p.last_name_with('-') # -
p.last_name_with("@")

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment