Created
February 22, 2012 23:09
-
-
Save ahoward/1888244 to your computer and use it in GitHub Desktop.
worlds simplest presenter pattern. drop in replacement for ActiveRecord/Mongoid models in your controller
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
# the worlds lightest weight presenter pattern. to use simply | |
# | |
# file app/presenters/post_presenter.rb | |
# | |
# PostPresenter = | |
# Presenter.for(Post) do | |
# validates_presence_of :custom_field_for_this_form | |
# | |
# end | |
# | |
# works with ActiveRecord and Mongoid models | |
# | |
begin | |
require 'rails_helper' | |
rescue LoadError | |
end | |
class Presenter | |
def Presenter.for(model, &block) | |
Class.new(model).class_eval do | |
presenter = self | |
singleton_class = class << presenter; self; end | |
singleton_class.module_eval do | |
define_method(:model_name){ model.model_name } | |
end | |
if model.respond_to?(:table_name) | |
presenter.set_table_name(model.table_name) | |
end | |
if model.respond_to?(:base_class) | |
singleton_class.send(:define_method, :base_class){ model.base_class } | |
end | |
if model.respond_to?(:collection_name) | |
presenter.collection_name = model.collection_name | |
end | |
if model.respond_to?(:hereditary?) | |
singleton_class.send(:define_method, :hereditary?){ false } | |
define_method(:hereditary?){ self.class.hereditary? } | |
end | |
define_method(:helper){ @helper ||= Helper.new } if defined?(Helper) | |
presenter.class_eval(&block) if block | |
presenter | |
end | |
end | |
end |
the block has to run after my setup, so i do need to run it manually.
I meant this:
Class.new(model).class_eval do
can be:
Class.new(model) do
Right?
oh @JEG2 - you're right. i'll right my fugly codez!
ps. i argued for years pre 'singleton_class' (vs metaclass). glad that turned out...
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Class.new() can take a block, so you don't need the class_eval().
You could also make use of Ruby 1.9's singleton_class() and define_singleton_method(), if you don't need to run on 1.8.