TrestleAdmin / trestle

A modern, responsive admin framework for Ruby on Rails
https://trestle.io
GNU Lesser General Public License v3.0
1.97k stars 177 forks source link

How i use concerns at trestle? #438

Open Guih12 opened 1 year ago

Guih12 commented 1 year ago

Guys, i'm with a problem. My question is how use concerns with trestle? Exist someaway of use?

joshmn commented 1 year ago

I don't have a great answer for this, but I've patched Trestle::Resource::Builder and modified some things at runtime before:

class Trestle::Resource::Builder
  def location_from_current_location
    params_with_location_from_current_attributes
    finder_scoped_location
    collection_scoped_location
  end

  def params_with_location_from_current_attributes
    self.class.include Hack
  end

  def collection_scoped_location
    admin.include CollectionHack
  end

  def finder_scoped_location
    admin.include FinderHack
  end

  module CollectionHack
    def prepare_collection(params, options={})
      if model.columns_hash['location_id']
        super.where(location_id: Current.location.id)
      else
        super
      end
    end
  end

  module FinderHack
    def find_instance(params)
      if model.columns_hash['location_id']
        model.find_by(id: params[:id], location_id: Current.location.id)
      else
        model.find(params[:id])
      end
    end
  end

  module Hack
    def params(&block)
      if admin.model.columns_hash['location_id']
        super.tap do |p|
          p[:location_id] = Current.location.id
        end
      else
        super
      end
    end
  end
end

And then in my admin resources:

Trestle.resource(:movies) do 
  location_from_current_location
end

It's ugly and feels awful but it got me what I needed.