Skip to content

Instantly share code, notes, and snippets.

@pataiji
Created July 11, 2014 10:30
Show Gist options
  • Save pataiji/76a103daa8ed2c8e9fc7 to your computer and use it in GitHub Desktop.
Save pataiji/76a103daa8ed2c8e9fc7 to your computer and use it in GitHub Desktop.
monkeypatch of wice_grid for draper support ( Inspired from https://github.com/leikind/wice_grid/issues/120 )
== grid(@posts_grid) do |g|
- g.column attribute: 'title'
- g.column name: 'body' do |u|
- u.truncated_body
class PostDecorator < Draper::Decorator
delegate_all
def truncated_body
object.body.truncate(15)
end
end
class PostsController < ApplicationController
def index
@posts_grid = initialize_grid Post, decorate: true
end
end
if defined?(Wice::WiceGrid) && defined?(Draper::CollectionDecorator) && defined?(Draper::Decorator)
module WiceGridDraperSupport
def initialize(klass_or_relation, controller, opts = {})
@decorate = opts.delete(:decorate)
super
end
def read
super
@resultset = @resultset.decorate(klass: @klass) if @decorate == true
end
end
module DraperCollectionWiceGridSupport
active_record_methods = [
:columns,
:connection,
:merge_conditions,
:page,
:table_name,
:unscoped,
:where
]
delegate *active_record_methods, to: :klass
active_record_relation_methods = [
:current_page,
:last_page?,
:limit_value,
:num_pages,
:offset_value,
:total_count,
:total_pages
]
delegate *active_record_relation_methods, to: :object
attr_reader :klass
def initialize(object, options = {})
@klass = options.delete(:klass)
super
end
def is_a?(klass)
klass == ActiveRecord::Relation || super
end
end
class Wice::WiceGrid
prepend WiceGridDraperSupport
end
class Draper::CollectionDecorator
prepend DraperCollectionWiceGridSupport
end
class Draper::Decorator
def self.decorate_collection(object, options = {})
options.assert_valid_keys(:with, :context, :klass)
collection_decorator_class.new(object, options.reverse_merge(with: self))
end
end
end
@Systho
Copy link

Systho commented Sep 26, 2014

I made a little tweak to allow the controller to specify which decorator to use.

  module WiceGridDraperSupport
    def initialize(klass_or_relation, controller, opts = {})
      @decorator = opts.delete(:decorator)
      super
    end

    def read
      super
       if @decorator < Draper::Decorator
         @resultset = @decorator.decorate_collection @resultset, klass: @klass
       elsif @decorator.present?
         @resultset = @resultset.decorate(klass: @klass)
       end
    end
  end

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment