Skip to content

Instantly share code, notes, and snippets.

@warmwaffles
Last active August 29, 2015 13:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save warmwaffles/9511492 to your computer and use it in GitHub Desktop.
Save warmwaffles/9511492 to your computer and use it in GitHub Desktop.
Hash Presenter demonstration
class SomePresenter < HashPresenter
present 'author', :author
present 'something', :something
present 'foo', :foo
def baz
"#{self.author} is #{self.something}"
end
end
presenter = SomePresenter.new({
'author' => 'Matthew',
something: 'important',
foo: {
bar: 'qux'
}
})
presenter.foo #=> { "bar" => "qux" }
presenter.author #=> 'Matthew'
presenter.baz #=> 'Matthew is important'
# A very light wrapper for a hash. It will allow you to present the hash in
# an object like manner without a ton of extra cruft
class HashPresenter
def self.present(key, as, options={})
options = { writer: true, reader: true }.merge(options)
reader = as
writer = "#{as}="
if options[:reader]
define_method(reader) do
self[key]
end
end
if options[:writer]
define_method(writer) do |object|
self[key] = object
end
end
end
def initialize(params={})
@hash = ActiveSupport::HashWithIndifferentAccess.new(params)
end
def [](key)
@hash[key]
end
def []=(key, value)
@hash[key] = value
end
def fetch(key, default=nil, &block)
if respond_to?(key)
value = self.send(key)
if value
value
else
block_given? ? yield(key) : default
end
else
@hash.fetch(key, default, &block)
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment