Forum: Ruby on Rails How to pass arguments to functions in callbacks in model ?

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
4012b0658c1e6e940414141efcf06ce6?d=identicon&s=25 Arpit Jain (Guest)
on 2009-05-24 09:55
(Received via mailing list)
I need to pass attributes to the function called in callback in rails
model.  For example,

after_save :update_something
after_destroy :update_something, true  #true is the argument that I need
to
pass

private
def update_something(value = false)
  #...
end


I found a way to do it like this

after_save :update_something
after_destroy {|record| record.update_something(true)}

But in this case, I need to make the function update_something public,
which
I don't want to do.

Any help ?


--
Arpit Jain
5fc9a2cb55d51b101285d60afebdc9c6?d=identicon&s=25 Erdwin Lianata (Guest)
on 2009-05-24 20:00
(Received via mailing list)
What about ...

def update_something(value=false)
   # ..
end

def after_save
   update_something(true)
end


Or use instance variable as conditional state instead of passing
variable to a function called from macro (i.e after_save)
25d73c90739bc1ba9835f770423557cf?d=identicon&s=25 Samiron Rony (samiron)
on 2009-05-25 11:23
(Received via mailing list)
You can use ActiveRecord::Observer. For details please go to
http://blog.invisible.ch/files/rails-reference-1.1.html

However theres another funny work around for this problem
as your desired syntax is
after_destroy :update_something, true

Just tweak little bit:
after_destroy "update_something(true)"

declare the update_something method privately like:
def update_something(param = value)
   #operations based on #{param}
end

I dont know your actual scenario. But i think
 * If u need to perform same action on :after_save and :after_destroy
call-back then why do you need parameter
 * Secondly, if update_something performs differently based on the
parameter then why don't you create two separate methods

Anyway looking for the real picture from you and hope to get the best
architectural suggestion from anyone for this kind of problem :-)

Thank you
Samiron Paul
http://samironpaul.blogspot.com


On May 24, 9:52 pm, Erdwin Lianata <erdwin.lian...@yahoo.com.sg>
This topic is locked and can not be replied to.