Last active
August 29, 2015 13:57
-
-
Save warmwaffles/9511492 to your computer and use it in GitHub Desktop.
Hash Presenter demonstration
This file contains 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
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' |
This file contains 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
# 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