yatish mehta
yatish mehta

Reputation: 915

around_action in rails with passing arguments?

How do I call around_action in Rails that accepts arguments?

around_action only: [:follow] do
 set_follow_source(@source)
end

def set_follow_source
  puts 'before'
  yield
  puts 'after'
end

Upvotes: 2

Views: 2344

Answers (3)

BitOfUniverse
BitOfUniverse

Reputation: 6021

It is possible and here is an example from Rails code:

 set_callback :save, :around, ->(r, block) { stuff; result = block.call; stuff }

so you just need to pass the block to your around filter like that:

around_action only: [:follow] do |_, blk|
 set_follow_source(@source, &blk)
end

def set_follow_source
   puts 'before'
   yield
   puts 'after'
end

Upvotes: 0

Nick Roz
Nick Roz

Reputation: 4250

I have to clarify your question. Who or what component exactly should set this argument?

In case you want to create some DSL so as to set an argument beforehand for around action, you can do something like that:

def self.say_hello_to(name)
  lambda do |controller, block|
    hello name, &block
  end
end

around_action say_hello_to('smith'), only: :index

def index
end

private

def hello(name, &block)
  puts 'hello'
  yield
  puts name
end

Upvotes: 1

BitOfUniverse
BitOfUniverse

Reputation: 6021

Actually, it already accepts some arguments, you can access controller instance as argument in the action filter callback, like this:

around_action only: [:follow] do |controller, block|
  controller.send(:any_method); 
  block.call # or yield
end

looks like it's okay to do this kind of things in Rails, you can find similar example in Rails docs paragraph 8.2

Upvotes: 0

Related Questions