ruby-on-railsargument-error

ROR: wrong number of arguments (given 2, expected 1)


On the following piece of code

def initialize(clause)
      clause =~ /^([\w\_\.]+)(->'\w+')?_(desc|asc)$|^([\w\_\.]+->>'[\w\_]+')(->'\w+')?_(desc|asc)$/
      @column = $1 || $4
      @op = $2 || $5
      @order = $3 || $6
      @field = [@column, @op].compact.join
    end

I am getting the following error

ArgumentError (wrong number of arguments (given 2, expected 1)):
  config/initializers/order_clause.rb:5:in `initialize' 

Does anyone knows how to resolve it? Please Help!

EDIT - I am adding the full code for more clarification.

module ActiveAdmin
  class OrderClause
    attr_reader :field, :order

    def initialize(clause)
      clause =~ /^([\w\_\.]+)(->'\w+')?_(desc|asc)$|^([\w\_\.]+->>'[\w\_]+')(->'\w+')?_(desc|asc)$/
      @column = $1 || $4
      @op = $2 || $5
      @order = $3 || $6
      @field = [@column, @op].compact.join
    end

    def valid?
      @field.present? && @order.present?
    end

    def to_sql(active_admin_config)
      table = column_in_table?(active_admin_config.resource_column_names, @column) ? active_admin_config.resource_table_name : nil
      if json_column?(@column)
        table_column = (@column =~ /\./) ? @column : [table, @column].compact.join(".")
        ['(', table_column, @op, ' ',')::numeric ', @order].compact.join
      else
        table_column = (@column =~ /\./) ? @column : [table, active_admin_config.resource_quoted_column_name(@column)].compact.join(".")
        [table_column, @op, ' ', @order].compact.join
      end
    end

    private

    def json_column?(column)
      column.include?('->>')
    end

    def column_in_table?(names, column)
      column = json_column?(column) ? column.split('->>')[0].strip : column
      names.include?(column)
    end
  end
end


Solution

  • The activeadmin gem instantiates the ActiveAdmin::OrderClause class with a couple of arguments (active_admin_config and order) as you can see here and here. Fix the initialize method arguments.

    def initialize(active_admin_config, clause)
      # ... 
    end
    

    You should also remove the active_admin_config argument from the to_sql method since it is called with no arguments. You can set @active_admin_config in the initialize method and add :active_admin_config to the attr_reader call to use in the to_sql method.

    module ActiveAdmin
      class OrderClause
        attr_reader :field, :order, :active_admin_config
    
        def initialize(active_admin_config, clause)
          @active_admin_config = active_admin_config
          # rest of the code
        end
    
        def to_sql
          # ...
        end
      end
    end
    

    I would recommend you create a CustomOrderClause class that inherits from the gem's ActiveAdmin::OrderClause class and only override the necessary methods. You can then use config.order_clause = CustomOrderClause when configuring activeadmin in an initializer.