public
Last active

worlds simplest presenter pattern. drop in replacement for ActiveRecord/Mongoid models in your controller

  • Download Gist
presenter.rb
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
# 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

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.

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...

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.