Sha256: 94e53a0a76609bfee2af7fd8e2e9962ad5f4245d905fcd7bb9b8e99ab53f4dac

Contents?: true

Size: 1.94 KB

Versions: 1

Compression:

Stored size: 1.94 KB

Contents

require 'ruhl/rails/active_record'
require 'ruhl/rails/helper'

module Ruhl
  module Rails
    class Presenter
      include Ruhl::Rails::ActiveRecord
      include Ruhl::Rails::Helper
  
      attr_reader :presentee, :context
  
      def initialize(context, obj = nil)
        @context = context

        # May only want to use the form helper
        if obj
          @presentee = obj
          define_paths(obj.class.name.underscore.downcase)
        end
      end
    
      def method_missing(name, *args)
        # Pass presenter method call to model so you don't have to
        # redefine every model method in the presenter class.
        presentee.__send__(name, *args)
      rescue NoMethodError 
        # Instead of saying context.link_to('Some site', some_path)
        # can just use link_to
        context.__send__(name, *args)
      end

      # Extend scope of respond_to? to model.
      def respond_to?(name)  
        if super
          true
        else
          presentee.respond_to?(name)
        end
      end  
    end
  end
end

module ActionController
  class Base    

    protected

    def present(options = {})
      action_sym = options[:action] || action_name
      object_sym = options[:object] || controller_name.singularize

      params = { :template => "#{controller_name}/#{action_sym}", 
                 :locals => {:object => presenter_for(object_sym) } }

      params[:layout] = options[:layout] if options.has_key?(:layout)

      render params
    end

    def presenter_for(object)

      if object.is_a?(Symbol) || object.is_a?(String)
        # Set instance variable if it exists
        if instance_variables.include?("@#{object}")
          obj = instance_variable_get("@#{object}")
        end
        name = object.to_s.camelize
      else
        name = object.class.name.camelize
        obj = object
      end

      Object.const_get("#{name}Presenter").new(@template, obj)
    end

    helper_method :presenter_for   
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
ruhl-1.1.0 lib/ruhl/rails/ruhl_presenter.rb