Sha256: 28ed38f5c95465984071bffd37d8bc42b68af2f1c2fb55ff6f3b7d6433c52acc

Contents?: true

Size: 1.82 KB

Versions: 1

Compression:

Stored size: 1.82 KB

Contents

require 'params_keeper/helper'

module ParamsKeeper::Controller
  extend ActiveSupport::Concern

  included do
    class_attribute :keep_params_keys, :keep_params_configs
    helper ParamsKeeper::Helper
  end

  def url_for(options = nil)
    return super if options.is_a?(Hash) && options.delete(:keep_params) == false

    configs = self.class.keep_params_configs
    keys = self.class.keep_params_keys
    return super if keys.blank?

    if configs.key?(:args)
      args = Array(configs[:args])
      return super if (options.is_a?(Hash) && !args.include?(:hash)) ||
                      (options.is_a?(String) && !args.include?(:string)) ||
                      (options.class.respond_to?(:model_name) && !args.include?(:model))
    elsif !options.is_a?(Hash)
      return super
    end

    if options.is_a?(Hash)
      if keep_params?(options, configs)
        super(ParamsKeeper::Helper.merge_params(options, params, keys))
      else
        super
      end
    else
      url = super(options)
      url_opts = begin
                   Rails.application.routes.recognize_path(url)
                 rescue ActionController::RoutingError
                   nil
                 end
      if url_opts && keep_params?(url_opts, configs)
        super(ParamsKeeper::Helper.merge_params(url_opts, params, keys))
      else
        url
      end
    end
  end

  def keep_params?(options, configs)
    controller = options[:controller].to_s
    if configs[:to]
      target = [controller, controller_name, controller_path]
      Array(configs[:to]).any? { |c| c.to_s.in?(target) }
    else
      controller.blank? || controller.in?([controller_name, controller_path])
    end
  end

  class_methods do
    def keep_params(*args)
      self.keep_params_configs = args.last.is_a?(Hash) ? args.pop : {}
      self.keep_params_keys = Array(args)
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
params_keeper_rails-1.0.0 lib/params_keeper/controller.rb