Skip to content
Create a gist now

Instantly share code, notes, and snippets.

worlds simplest presenter pattern. drop in replacement for ActiveRecord/Mongoid models in your controller
# 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
@JEG2
JEG2 commented Feb 22, 2012

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.

@ahoward
Owner
ahoward commented Feb 23, 2012

the block has to run after my setup, so i do need to run it manually.

@JEG2
JEG2 commented Feb 23, 2012

I meant this:

Class.new(model).class_eval do

can be:

Class.new(model) do

Right?

@ahoward
Owner
ahoward commented Feb 23, 2012

oh @jeg2 - you're right. i'll right my fugly codez!

@ahoward
Owner
ahoward commented Feb 23, 2012

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
Something went wrong with that request. Please try again.