Skip to content

Instantly share code, notes, and snippets.

@jonahoffline
Last active December 19, 2015 14:18
Show Gist options
  • Save jonahoffline/5967941 to your computer and use it in GitHub Desktop.
Save jonahoffline/5967941 to your computer and use it in GitHub Desktop.
Refactor example (Before / After) for Predicate method magic in a class I made for the link_shrink gem.
# Old:
module LinkShrink
class Options < Hash
def initialize(*args)
super(*args)
self.merge!(self.default)
end
def qr_code?
self.fetch(:qr_code, false)
end
def json?
self.fetch(:json, false)
end
def image_size?
self.fetch(:image_size, '150x150')
end
end
end
# Refactor:
module LinkShrink
class Options < Hash
def initialize(*args)
super(*args)
self.merge!(self.default)
end
returns = { qr_code: false, json: false, image_size: '150x150' }
returns.map do |method, default_value|
define_method "#{method}?" do
self.fetch(method, default_value)
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment