aforalegria
aforalegria

Reputation: 370

Rails before_filter different arguments

I have controller actions which all use one method but with different arguments. Can I refactor this somehow to use before_filter?

  def usd_cash
    transaction_currency("USD cash")
  end

  def usd_bank
    transaction_currency("USD bank")
  end

  def rub_bank
    transaction_currency("RUB bank")
  end

  private

  def transaction_currency(currency)
    @transactions = Transaction.where(location: "#{currency}")
  end

Upvotes: 0

Views: 183

Answers (2)

Andrey Deineko
Andrey Deineko

Reputation: 52347

You could use some metaprogramming, but this would not be as readable as what you currently have:

%i(
  usd_cash
  usd_bank
  rub_bank
).each do |method|
  define_method method do
    transaction_currency(method.to_s.split('_').instance_eval {first.upcase + ' ' + last})
  end
end

Upvotes: 3

Sajjad Murtaza
Sajjad Murtaza

Reputation: 1504

You can try this way.You can call usd_type like before_filter { usd_type("RUB bank")}

I supposed here you do this before filter, You can change with your own requirement.

def usd_type(type)
  transaction_currency(type)
end

private

def transaction_currency(currency)
  @transactions = Transaction.where(location: "#{currency}")
end

Upvotes: 0

Related Questions