bogdan / datagrid

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

How to get key from current filter? #249

Closed PirunSeng closed 5 years ago

PirunSeng commented 6 years ago

Hi There, thanks for a very cool gem.

I'm having this sample filter:

  filter(:name, :string) { |value, scope, grid|} do
    ...
  end

How can we get key from this filter which is either :name or "name" in this case? I want to use that key to do something inside that block. I had also posted the same question in stackoverflow here. On the other hand, I wonder if somebody could create datagrid-gem tag to stackoverflow.

bogdan commented 6 years ago

From the snippet above, just write :name instead of variable, why not? I depends on the context you are trying to use it.

If you are trying to share some code between filters, you can do that in many different ways like:

filter(:name, ....) do |value, scope, grid|
  grid.shared_filter_code(:name, value, scope, grid)
end
def shared_filter_code(name, *args)
   # write code using name and args
end
# or
def self.shared_code_filter(name, *args)
  filter(name, *args) do |*arguments|
     # write code using arguments and name
  end
end
shared_code_filter(:name :string)
PirunSeng commented 6 years ago

@bogdan thanks! Of course, I've done that. I just wonder if there is a more dynamically or better way to get the key. My scenario is to prevent a case that the developer might change the key of the filter, but they forget to also change the argument of that key. Eg:

filter(:name_changed, ...) do |value, scope, grid|
  grid.shared_filter_code(:name, value, scope, grid)
end
bogdan commented 6 years ago
alias_method :name=, :name_changed=
alias_method :name, :name_changed

Enjoy! You may not need the second method aliasing only the writer. It depends on your use case.