bogdan / datagrid

Gem to create tables grids with sortable columns and filters
MIT License
1.02k stars 116 forks source link

how to wrap the model instances #179

Closed ktec closed 8 years ago

ktec commented 8 years ago

Sorry if this is the wrong place to ask, but I would like to wrap the models using a Presenter. To explain my situation here is an example:

Assume I wish to show a list of Users, I create the controller like this:

  def index
    @users_grid = UsersGrid.new(params[:users_grid]) do |scope|
      scope.page(params[:page])
    end
  end

So I can decorate the model in the block with each column like this:

class UsersGrid
  include Datagrid

  scope do
    User
  end

  column(:fullname) do |model|
    UserPresenter.decorate(model).full_name
  end

  column(:profile) do |model|
    UserPresenter.decorate(model).profile
  end
end

But as you can see I have to do this for every attribute I wish to decorate. Is there any way I can decorate the model before its passed to the block, so that I don't have to do it in every column definition?

Finally, thanks for a great gem, I've really enjoyed using it.

bogdan commented 8 years ago

Here is what you can do:

def self.decorated_column(name, options = {}, &block)
  column(name, options) do |model|
    presenter = UserPresenter.decorate(model)
    block ? block.call(presenter) : presenter.send(name)
 end
end
decorated_column(:fullname)
decorated_column(:profile)

I saw a request to create a decorator before, maybe I'll add this feature to the gem soon.

ktec commented 8 years ago

Wonderful, thanks thats really helpful 👍

You could add a comment on the read me about this, it would be useful I think.