Sha256: 2ac4535c5544d7233b1093c59a837e7cb102e10340d8b70c54e9d8cdb7d05ed6

Contents?: true

Size: 1.66 KB

Versions: 1

Compression:

Stored size: 1.66 KB

Contents

module ActiveRecordPresenter
  def error_messages?
    !presentee.errors.empty?
  end
  
  def error_messages
    return if presentee.errors.empty?
    presentee.errors.full_messages
  end
  
  # Pass presenter method call to model so you don't have to
  # redefine every model method in the presenter class.
  def method_missing(name, *args)
    if presentee.respond_to?(name)
      presentee.send(name, *args)
    end
  end

  # Extend scope of respond_to? to model.
  def respond_to?(name)  
    if super
      true
    else
      presentee.respond_to?(name)
    end
  end
  
  def define_paths(model)
    define_action(model, 'show')                      # show_path(@user)
    define_action(model, 'update')                    # update_path(@user)
    define_action(model, 'delete')                    # delete_path(@user)
    define_action("edit_#{model}", 'edit')            # edit_path(@user)
    define_action(model.pluralize, 'index', false)    # index_path
    define_action(model.pluralize, 'create', false)   # create_path
    define_action("new_#{model}", 'new', false)       # new_path
  end
  
  private
  
  def define_action(model, action, use_presentee = true)
    if use_presentee
      self.class.send(:define_method, "#{action}_path") do
        context.send("#{model}_path", presentee)
      end      
      self.class.send(:define_method, "#{action}_url") do
        context.send("#{model}_url", presentee)
      end      
    else
      self.class.send(:define_method, "#{action}_path") do
        context.send("#{model}_path")
      end      
      self.class.send(:define_method, "#{action}_url") do
        context.send("#{model}_url")
      end      
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
ruhl-0.12.0 lib/ruhl/rails/active_record_presenter.rb